【发布时间】:2014-11-24 20:35:29
【问题描述】:
我有带有自定义AuthorizeAttribute 的 ASP.NET MVC4 项目来控制授权。为了更容易解释我的情况,我创建了一个虚拟项目来说明问题。
我只有一个控制器
using System.Web.Mvc;
using MvcApplication2.Helper;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(ViewModel model)
{
Session["ModelValue"] = model.InputValue;
return RedirectToAction("Step2");
}
[MyAuthorize]
public ActionResult Step2()
{
return View();
}
}
}
目的很简单,从Index 我接受一些输入,将值存储在会话中并重定向到Step2。我在第 2 步有我的授权属性。我的属性的代码是
using System;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication2.Helper
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Session["ModelValue"] == null)
{
return false;
}
else
{
string inputValue = httpContext.Session["ModelValue"] as string;
if (inputValue != "1")
{
return false;
}
else
{
return true;
}
}
}
}
}
目的很简单,检查session值是否为1。
运行应用程序,在文本框中输入 1 并看到 step2 视图,如果输入其他任何内容,则会得到默认的 401.0 页面。
现在我打开了web.config 文件以包含
<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
<error statusCode="401" redirect="~/401.htm" />
</customErrors>
<compilation debug="true" targetFramework="4.0" />
</system.web>
我希望当应用程序捕获 401 代码时,我应该看到 401.htm 的内容。但现实情况是,我仍然从服务器获得默认的 401 错误显示。
知道为什么吗?
【问题讨论】:
-
我见过很多这样的实现,但我仍然试图理解为什么 web.config 更改根本不起作用。
标签: asp.net-mvc-4 http-status-code-401