私はこのようにそれを行うだろう:
public class CustomErrorObject
{
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class HandleApiExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
base.OnException(actionExecutedContext);
HttpRequestMessage request = actionExecutedContext.ActionContext.Request;
CustomErrorObject response = new CustomErrorObject();
response.ErrorCode = actionExecutedContext.Exception.Data("Text");
response.ErrorDescription = actionExecutedContext.Exception.Data("Detail");
actionExecutedContext.Response = request.CreateResponse(HttpStatusCode.BadRequest, response);
}
}
を次にGlobal.asaxの中のApplication_Startイベントに次の行を追加します。
GlobalConfiguration.Configuration.Filters.Add(new HandleApiExceptionAttribute())
を使用すると、例外処理についての詳細をお知りになりたい場合はin Web API:here