【问题标题】:not found exception is not working in web api [closed]未找到异常在 web api 中不起作用 [关闭]
【发布时间】:2015-12-18 20:17:43
【问题描述】:

我的代码

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."

}

据我所知,我需要“此项目已存在”之类的消息。请帮帮我

【问题讨论】:

  • 您正在抛出异常,并得到异常。多么令人费解!代码完全按照您所说的做!你能edit解释一下这有什么意外吗?
  • 为什么“此项目不存在”的消息没有出现
  • 您确定以正确的方式调用服务吗?你可以发布你的电话吗?

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


【解决方案1】:

您的实现确实按预期工作。您是否正确调用 API?我使用了 TestController 并发布到以下 Uri 并且它可以工作:

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

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

return this.NotFound();

返回 NotFound 错误是告诉调用客户端它需要知道的一切,返回“此项目不存在”是多余的。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2021-09-15
    • 1970-01-01
    • 2017-06-16
    • 2012-12-18
    • 2013-03-07
    相关资源
    最近更新 更多