简体   繁体   English

有没有办法让AuthorizeAttribute响应状态代码403 Forbidden而不是重定向?

[英]Is there a way to make AuthorizeAttribute respond with status code 403 Forbidden rather than a redirect?

If the user is not logged in and they request an action marked [Authorize] , then the response is a redirect to the Account/LogOn action (status code 302 Found). 如果用户未登录并且他们请求标记为[Authorize] ,则响应是重定向到帐户/登录操作(状态代码302 Found)。

Is there a way to make the response be status code 403 Forbidden instead? 有没有办法让响应成为状态代码403 Forbidden?

Create an action filter that inherits from AuthorizeAttribute . 创建一个继承自AuthorizeAttribute的操作筛选器。 Then override this method: 然后覆盖此方法:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{ 
   Response.StatusCode = 403;
   Response.Status = "Forbidden";
   Response.StatusDescription = "Forbidden";
   Response.End();
   Response.Close();

}

If the user is not logged in then the more appropriate status code is 401:Unauthorized. 如果用户未登录,则更合适的状态代码为401:未授权。 This is what the AuthorizeAttribute returns by default. 这是AuthorizeAttribute默认返回的内容。

FormsAuthenticationModule will catch this return code and convert it into the redirect. FormsAuthenticationModule将捕获此返回代码并将其转换为重定向。 If you can disable (or not even load it) then this will be returned to the caller. 如果您可以禁用(或甚至不加载它),那么这将返回给调用者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在代码中检查 ASP.NET 身份验证策略而不是使用 AuthorizeAttribute? - How to check ASP.NET auth policy in code rather than using AuthorizeAttribute? 在哪里返回 403 禁止状态? - Where to return 403 Forbidden Status? 为什么我的自托管WCF服务返回403 Forbidden,而不是401 Unauthorized? - Why is my self-hosted WCF service returning 403 Forbidden, rather than 401 Unauthorized? 将 ActionResult 而不是 IActionResult 转换为 OKObjectResult 以测试 200 状态代码? - Casting an ActionResult rather than IActionResult to an OKObjectResult for testing a 200 status code? 禁止状态代码 403 无法在 wsdl Web 服务上使用 postAsync 方法对多部分数据进行编码? - Status code 403 forbidden unable to encode multipartform data using postAsync method on wsdl webservice? 重定向到 Blazor WebAssembly 中的 403 Forbidden 组件 - Redirect to 403 Forbidden component in Blazor WebAssembly 编写此代码而不是2x foreach的更好方法? - Better way to write this code rather than 2x foreach? 有没有办法在代码中而不是在配置文件中设置配置运行时选项? - Is there a way to set configuration runtime options in code rather than in the config file? nUnit中的代码工作正常,但Windows Service中的代码获得HTTP状态403:调用远程Web服务时被禁止 - Code within nUnit works fine but within Windows Service gets HTTP status 403: Forbidden when calling a remote Web Service 无法从 Jenkins 有问题地获取最后构建状态 - 403 禁止 - Cant get Last build status problematically from Jenkins - 403 forbidden
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM