Exception handling 如何在web api 2中记录badrequest?
是否有方法捕获并记录web api 2中某个操作的badrequest或未经授权的响应代码? 我尝试添加一个ActionExecuted attributefilter和ExceptionLogger,但两者都不起作用Exception handling 如何在web api 2中记录badrequest?,exception-handling,asp.net-web-api,Exception Handling,Asp.net Web Api,是否有方法捕获并记录web api 2中某个操作的badrequest或未经授权的响应代码? 我尝试添加一个ActionExecuted attributefilter和ExceptionLogger,但两者都不起作用 public IHttpActionResult ConfirmUpload(string val) { if (String.IsNullOrWhiteSpace(val)) return BadRequest(val); } public static v
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
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包含有关请求的信息,所以如果需要,您可以检查请求状态。属性可以应用于控制器、操作
public class ValueController : ApiController
{
[Log]
public IEnumerable<object> Get()
{
}
}
此外,还可以在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();
}
你好,谢谢你的回复。我以前已经试过了。我猜测的是返回错误请求(val);不是web api的例外,因此它不会捕获它。我将尝试使用actionfilters。还有一个OnResultExecuted方法可能会对您有所帮助。该方法是为web api定义的还是仅为mvc定义的?很抱歉误导您,OnResultExecuted未为web api定义
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();
}