在ASP.NET MVC 5中,可以使用自定义的ActionFilterAttribute来实现在302重定向时返回401状态码的功能。
步骤如下:
创建一个名为CustomAuthorizeAttribute的自定义的ActionFilterAttribute,继承于AuthorizeAttribute。
在CustomAuthorizeAttribute中重写OnAuthorization方法,当授权未通过时返回401状态码。
在需要进行授权判断的Action或Controller上添加CustomAuthorizeAttribute标签即可。
代码示例:
// CustomAuthorizeAttribute.cs
using System.Web.Mvc;
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new HttpStatusCodeResult(401);
}
}
}
// HomeController.cs
public class HomeController : Controller
{
[CustomAuthorize]
public ActionResult Index()
{
return View();
}
}