【问题标题】:Is it possible to show Error Message in VOID type for webapi?是否可以为 webapi 显示 VOID 类型的错误消息?
【发布时间】:2017-05-03 14:36:34
【问题描述】:

我是 Web Api 2 的新手,如果我点击 Exception ,我想显示一些消息,我知道 VOID 是非返回类型,我尝试使用 HttpResponseMessage 但它不起作用或显示“错误消息”,这是显示消息的任何方式吗?

我的代码如下

 public void Post(int id)
 {

        string result = string.Empty;
        try
        {
          //some code
        }
        catch (Exception ex)
        {
            HttpResponseMessage response2 = Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");
            ErrId = 999;
        }
 }

【问题讨论】:

  • 如果你遇到了异常,那么 ex.Message 应该会告诉你你需要什么。
  • @Wheels73 可以在异常部分显示一些示例?
  • 只需将“错误消息”替换为 ex.Message。
  • 使用public void Post(int id) 似乎有点可疑。这看起来像一个名为“post”的 GET 方法。你确定你真的调用了正确的函数吗?
  • 是什么阻止您返回您在catch 块中创建的response2 结果?如果成功,返回 Created() 或 Ok()。

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


【解决方案1】:

如果您使用的是 web api 2,那么我会使用 IHttpActionResult 作为返回类型,它允许您执行以下操作:

public IHttpActionResult Post(int id)
{
        string result = string.Empty;
        try
        {
          //some code
          return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest("Error message");
        }
 }

但是,必须注意的是,默认情况下 Web API 有一个内置的异常处理程序和记录器,对于任何异常都会自动返回 500 响应代码,因此上面的代码可能是多余的,除非您正在捕获自定义异常。最后上面的代码没有记录异常。

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多