C#MVC:如何覆盖已配置的身份验证重定向?

时间:2011-04-01 22:10:27

标签: c# model-view-controller authentication web-config

我在Web.config中有一个带有以下块的MVC应用程序:

<authentication mode="Forms">
    <forms loginUrl="~/Login" timeout="2880" />
</authentication>

因此,如果用户请求页面并且授权失败,则会将其重定向到〜/ Login。

那很好,我的大多数控制器都需要它。但是,我有一个控制器,我想绕过这个规则。如何允许特定控制器忽略此规则?

我的问题是,在我的MVC应用程序(有几个控制器)中,我有一个控制器,它承载一个REST接口(不适合浏览器使用)。由于此控制器不适合浏览器使用,我不希望它发回整个登录页面(或任何实际页面,只是字符串或部分视图。)

请注意,我在我的操作中使用自定义[授权...]属性,当这些属性失败时,它们会重定向到错误操作 - 但不幸的是,我的错误操作(返回一个短字符串)由于此配置设置,正被重定向到登录页面

我头晕目眩,试图解决这个问题,我做错了什么?如有必要,我可以提供更多细节。

3 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:2)

在Web.config中的system.web元素之后添加以下内容:

<location path="home">
<system.web>
    <authorization>
        <allow users="*" />
    </authorization>
</system.web>
</location>

这将允许未经身份验证的用户访问“/ home”,从而访问HomeController上的任何操作。

答案 2 :(得分:0)

菲尔·哈克(Phil Haack)有一篇关于这个问题的博客文章非常详尽:Prevent Forms Authentication Login Page Redirect When You Don’t Want It