Jay*_*van 8 c# authentication model-view-controller web-config
我在Web.config中有一个带有以下块的MVC应用程序:
<authentication mode="Forms">
<forms loginUrl="~/Login" timeout="2880" />
</authentication>
Run Code Online (Sandbox Code Playgroud)
因此,如果用户请求页面并且授权失败,则它们将被重定向到〜/ Login.
那很好,我的大多数控制器都需要它.但是,我有一个控制器,我想绕过这个规则.如何允许特定控制器忽略此规则?
我的问题是,在我的MVC应用程序(有几个控制器)中,我有一个托管REST接口的控制器(不适合浏览器使用).由于此控制器不适合浏览器使用,我不希望它发回整个登录页面(或任何实际的页面,只是字符串或部分视图.)
请注意,我在我的操作中使用自定义[授权...]属性,当这些属性失败时,它们会重定向到错误操作 - 但不幸的是,我的错误操作(返回一个短字符串)被重定向到登录页面因为此配置设置!
我头晕目眩,试图解决这个问题,我做错了什么?如有必要,我可以提供更多细节.
Roh*_*est 11
您可以扩展AuthorizeAttribute类并覆盖HandleUnauthorizedRequest,您可能希望返回Forbidden http状态代码而不是自定义消息.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4210 次 |
| 最近记录: |