未找到异常在web api中不起作用

时间:2015-12-18 03:04:02

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

我的代码

public async Task<IHttpActionResult> Post(long? Workrequestid, string fileexist){ throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound,"this item does not exist"));}

错误我变得像

{  "message": "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details."

}

据我说,我需要像&#34这样的信息;这个项目已经存在&#34;。请帮帮我

1 个答案:

答案 0 :(得分:1)

您的实施确实按预期工作。你正确地调用API了吗?我已经使用了TestController并发布到以下的Uri,它可以工作:

  

http://localhost:8075/api/test?workrequestId=1&fileexist=test

但是,您确定要显式抛出异常吗?返回IHttpActionResult时,以下列方式返回404会更简洁:

return this.NotFound();

返回NotFound错误告诉调用客户端需要知道的所有内容,返回&#34;此项目不存在&#34;是多余的。

由于您的代码示例没有实现,因此很难看到您对API的意图,以及它的帖子。根据具体情况 ,如果合适 ,您还可以返回:

return this.BadRequest("this item does not exist.");