如何在ASP.NET MVC4中捕获Web API中的表单授权错误

 请让我来打酱油 发布于 2023-02-14 00:55

ASP.NET/Mono MVC4 Web API v.1应用程序.

API控制器使用表单授权,并使用标准[Authorize]属性进行修饰.如果授权失败,则标准api错误消息


Authorization has been denied for this request.

发生.如何通过写入日志文件来识别此错误.返回给调用者shoudl的错误消息保持不变.如何添加额外的代码,这可以写入此错误消息与整个http请求标头和正文到日志文件?

我从问题中添加了代码

如何为C#MVC4 WebAPI应用程序全局记录所有异常?

如何在ASP.NET MVC4 Web API中捕获未定义的api方法调用

但是没有抓住错误的错误.

如何捕捉所有错误?

更新

代码需要在Windows 2003服务器中运行.我从回答中尝试了代码,但遇到了编译错误

Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported

Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?

Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?

如何在W2003服务器中运行int?

1 个回答
  • 实现此目的的一种方法是编写DelegatingHandler以在响应被发送回客户端之前拦截响应,然后记录有关返回错误的请求的信息.

    public class RepsonseInterceptor : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
    
            LogResponse(request, response);
    
            return response;
        }
    
        public void LogResponse(HttpRequestMessage request, HttpResponseMessage response)
        {
            HttpStatusCode status = response.StatusCode;
            //Catch the status codes you want to Log
            if (status == HttpStatusCode.NotFound || status == HttpStatusCode.Unauthorized || status == HttpStatusCode.InternalServerError)
            {
                //Do Logging Stuff here
                //with the Request and Response
            }
        }
    }
    

    然后将其添加到Global.asax.cs中的Application_Start:

    GlobalConfiguration.Configuration.MessageHandlers.Add(new ResponseInterceptor());
    

    编辑:

    如果您不想为所有路由执行处理程序,可以将它作为Per-Route消息处理程序添加到您想要的路由而不是全局路由,如下所示:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: null,
        handler: new ResponseInterceptor()
        );
    

    如果您使用的是.NET Framework 4.0,则需要更改处理程序的SendAsync方法,如下所示:

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return base.SendAsync(request, cancellationToken)
          .ContinueWith(task =>
          {
              var response = task.Result;
              LogResponse(request, response);
              return response;
           });
    }
    

    我认为如果你能从请求和响应对象中获取所需的所有信息,那么使用这个MessageHandler是合理的,尽管我还没有完全测试过.

    2023-02-14 01:25 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有