C#MVC:如何重写配置的认证重定向? [英] C# MVC: How to override configured authentication redirect?
问题描述
我有以下块的Web.config内的MVC应用程序:
I have an MVC application with the following block inside in Web.config:
<authentication mode="Forms">
<forms loginUrl="~/Login" timeout="2880" />
</authentication>
所以,如果一个用户请求一个页面,并授权失败,他们将被重定向到〜/登录。
So, if a user requests a page and authorization fails, they will be redirected to ~/Login.
这很好,我需要我的大多数控制器。不过,我有我想绕过这个规则,它的控制器。我怎么能允许特定的控制器忽略此规则?
That's fine, and I need it for most of my controllers. However, I have a controller which I'd like to bypass this rule with. How can I allow specific controllers to ignore this rule?
我的问题是,在我的MVC应用程序(其中有几个控制器),我有一定的控制器,它承载一个REST接口(不是为浏览器使用)。由于该控制器并不意味着浏览器的消费,我不希望它发回一个完整的登录页面,(或任何实际上的页面,只是字符串或部分意见。)
My problem is that in my MVC application (which has several controllers), I have a certain controller which hosts a REST interface (not meant for browser use). Since this controller isn't meant for browser-consumption, I don't want it sending back an entire login page, (or any page whatsoever actually, just strings or partial views.)
请注意,我使用自定义[授权...]属性上我的动作,而当这些失败,他们重定向到一个错误的行动 - 但不幸的是,的我的错误动作(它返回一个字符串短)被重定向到登录页面的,因为此配置设置的!
Note that I'm using custom [Authorize...] attributes on my actions, and when THESE fail, they redirect to an Error action--but, unfortunately, my Error action (which returns a short string) is being redirected to the Login page because of this configuration setting!
我得到头晕试图弄清楚这一点,我究竟做错了什么?如果需要的话我可以提供更多的细节。
I'm getting dizzy trying to figure this out, what am I doing wrong? I can provide more details if necessary.
推荐答案
您可以扩展AuthorizeAttribute类并覆盖HandleUnauthorizedRequest,你可能要返回一个禁止HTTP状态code,而不是自定义消息。
You could extend the AuthorizeAttribute class and override HandleUnauthorizedRequest, you may want to return a Forbidden http status code rather than a custom message.
public class CustomAuthorizationAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// You need to set this action result to something other than a HttpUnauthorizedResult,
// this result will cause the redirection to the login page
// Forbidden request... does not redirect to login page
// filterContext.Result = new HttpStatusCodeResult(403);
filterContext.Result = new ErrorActionResult { ErrorMessage = "Unauthorized Access" };
}
}
public class ErrorActionResult : ActionResult
{
public string ErrorMessage { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write(this.ErrorMessage);
}
}
这篇关于C#MVC:如何重写配置的认证重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!