C#MVC : How to override configured authentication redirect?

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

我有一个 MVC 应用程序,在 Web.config 中包含以下 block :

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

因此,如果用户请求页面并且授权失败,他们将被重定向到 ~/Login。

很好,我的大部分 Controller 都需要它。但是,我有一个 Controller ,我想用它来绕过这个规则。我怎样才能让特定的 Controller 忽略这条规则?

我的问题是,在我的 MVC 应用程序(有多个 Controller )中,我有一个托管 REST 接口(interface)的特定 Controller (不适合浏览器使用)。由于此 Controller 不适合浏览器使用,我不希望它发回整个登录页面(或任何实际的页面,只是字符串或部分 View 。)

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

我在想办法解决这个问题时头晕目眩,我做错了什么?如有必要,我可以提供更多详细信息。

最佳答案

您可以扩展 AuthorizeAttribute 类并覆盖 HandleUnauthorizedRequest,您可能希望返回禁止的 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);
    }
}

关于C#MVC : How to override configured authentication redirect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5519393/

相关文章:

authentication - 使用相互 SSL 将 Glassfish 配置为 Web 服务的客户端

c# - 在 fluentassertion 上调用异步任务

javascript - 确保 javascript 函数按特定顺序执行

ruby-on-rails - Rails 类型的 webapp 中的 'Model' 如何用函数式编程语言实现?

java - Spring 安全。添加用户登录限制

php - 我是否在登录系统中使用 cookie 或 session 登录?

c# - 编译到 AnyCpu 时 LoadLibrary 不起作用

c# - 创建网格 - 什么是执行此操作的有效方法

c# - 使用 1D 柏林噪声创建粗略/摇摆线

c# - DataTables MVC 回发数据为空