asp.net – 当我试图强制401时,自定义授权过滤器总是返回404

前端之家收集整理的这篇文章主要介绍了asp.net – 当我试图强制401时,自定义授权过滤器总是返回404前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写自己的授权属性,在那里我使用CustomAuthorization属性对任何web api方法执行一些自定义检查.

我的代码如下:

  1. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = false,Inherited = false)]
  2. public class CustomAuthorization : AuthorizationFilterAttribute
  3. {
  4. public override void OnAuthorization(AuthorizationContext context)
  5. {
  6. //// Attempt 1 - 404 error.
  7. //// Doesnt block method with this attribute from executing (not desired behavIoUr).
  8.  
  9. //context.HttpContext.Response.StatusCode = 401;
  10. //return;
  11.  
  12. //// Attempt 2 - 404 result.
  13. //// Code with attribute doesnt execute (desired).
  14. //// Error thrown says: An exception of type 'System.Web.Http.HttpResponseException' occurred in <namespace> but was not handled in user code
  15. //// Additional information: Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.
  16.  
  17. //throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
  18.  
  19. // Attempt 3 - 404 result.
  20. // Code with attribute doesnt execute (desired).
  21. context.Result = new HttpUnauthorizedResult();
  22. }
  23. }

我遇到的问题是我从网络API而不是预期的401获得404响应.我做错了什么?

这是asp.net核心1.

提前致谢!

解决方法

这可能是因为您有身份验证设置重定向到401响应的登录页面,并且找不到登录页面(发生在我身上).

猜你在找的asp.Net相关文章