我正在尝试在我的WebAPI中实现错误处理,并且ErrorController.cs
包含以下代码:
public class ErrorController : ApiController
{
[HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions, AcceptVerbs("PATCH")]
public HttpResponseMessage Handle404()
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
responseMessage.ReasonPhrase = "The requested resource is not found";
return Request.CreateResponse(new { error = "The requested resource is not found" });
}
}
我这样做了一个API调用:
http://localhost:46151/api/TData?ROOM=ABC&DOB_GT=01-SEP-05&DOB_LT=30-DEC-06&STATUS_TYPE=CMT
为了强制发生错误,我尝试拼错其中一个查询参数(从DOB_LT
到DO_LT
)以检查错误的处理方式 - 如下所示:
http://localhost:46151/api/TData?ROOM=ABC&DOB_GT=01-SEP-05&DO_LT=30-DEC-06&STATUS_TYPE=CMT
调试器在ErrorController中断,如下图所示:
尝试像
一样尝试Catch block catch (Exception ex)
{
var returnObj = new { error = ex.Message };
var response = Request.CreateResponse(HttpStatusCode.BadRequest, returnObj, MediaTypeHeaderValue.Parse("application/json"));
ContentDispositionHeaderValue contentDisposition = null;
if (ContentDispositionHeaderValue.TryParse("inline; filename=error.json", out contentDisposition))
{
response.Content.Headers.ContentDisposition = contentDisposition;
}
return response;
}