Ayk*_*car 5 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());
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏。
Max*_*nov -1
要记录错误请求,您可以编写自己的从 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);
}
}
Run Code Online (Sandbox Code Playgroud)
HttpActionExecutedContext 包含有关请求的信息,以便您可以根据需要检查请求状态。属性可以应用于控制器、动作
public class ValueController : ApiController
{
[Log]
public IEnumerable<object> Get()
{
}
}
Run Code Online (Sandbox Code Playgroud)
或全局添加
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new LogAttribute());
}
}
Run Code Online (Sandbox Code Playgroud)
所有异常也可以在 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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1121 次 |
| 最近记录: |