Web API ArgumentNullException未被用户代码处理

时间:2016-11-22 04:05:11

标签: c# asp.net api asp.net-web-api

我正在尝试在我的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_LTDO_LT)以检查错误的处理方式 - 如下所示:

http://localhost:46151/api/TData?ROOM=ABC&DOB_GT=01-SEP-05&DO_LT=30-DEC-06&STATUS_TYPE=CMT

调试器在ErrorController中断,如下图所示:

enter image description here

尝试像

一样尝试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;
         }

0 个答案:

没有答案