gpt4 book ai didi

C#MVC : How to override configured authentication redirect?

转载 作者:太空狗 更新时间:2023-10-29 18:20:59 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com