exception-handling - 如何在 web api 2 中记录 badrequest?

标签 exception-handling asp.net-web-api

有没有办法从 web api 2 中的操作中捕获并记录错误请求或未经授权的响应代码?
我尝试添加 onactionexecuted attributefilter 和 ExceptionLogger 但它们都不起作用。

public IHttpActionResult ConfirmUpload(string val)
{
   if (String.IsNullOrWhiteSpace(val))
      return BadRequest(val);
}

public static void Register(HttpConfiguration config)
{
    AreaRegistration.RegisterAllAreas();
    config.Filters.Add(new ErrorLogAttribute());
    config.Services.Add(typeof(IExceptionLogger), new ErrorLogger());
}

任何帮助表示赞赏。

最佳答案

要记录错误的请求,您可以编写自己的从 ExceptionFilterAttribute 派生的 LogAttribute

public class LogAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        Log.Error(context.Exception);

        context.Response = context.Request.CreateResponse(
                HttpStatusCode.InternalServerError,
                new { message = context.Exception.InnerException != null ? context.Exception.InnerException.Message : context.Exception.Message });

        base.OnException(context);
    }
}

HttpActionExecutedContext 包含有关请求的信息,因此您可以根据需要检查请求状态。属性可以应用于 Controller 、 Action
public class ValueController : ApiController
{
    [Log]
    public IEnumerable<object> Get()
    {
    }
}

或全局添加
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new LogAttribute());
    }
}

也可以在 global.asax 中捕获所有异常
protected void Application_Error()
{
    var ex = Server.GetLastError().GetBaseException();

    // ignore 404
    if (!(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404))
    {
        Log.Fatal("Unhandled error catched in Global.asax", ex);
    }

    Server.ClearError();
}

关于exception-handling - 如何在 web api 2 中记录 badrequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22165285/

相关文章:

c# - ASP.Net Web API Controller 中具有相同路由名称的 Post Action 方法重载

asp.net-web-api - 使用ASP.NET MVC 6 WebAPI从Auth0获取用户信息

asp.net-web-api - Web API 2 是否可以以编程方式加载路由/ Controller ?

c++ - 使用 __debugbreak() 尝试/捕获

ios - 使用 swift 3 从 asp.net web api 中过滤来自 JSON 的字符串

C++ 捕获枚举值作为异常

python - 捕获不从 Exception 继承的异常

asp.net-mvc - ASP.NET MVC 中的漏洞测试

java - 抛出异常和捕获异常?

exception-handling - Spring Integration - 在服务激活器组件中发生异常时写入错误队列