【问题标题】:Custom HttpStatusCode without Error Message (HttpActionResult)没有错误消息的自定义 HttpStatusCode (HttpActionResult)
【发布时间】:2016-07-26 14:34:37
【问题描述】:

我目前正在从事 Asp.net WebAPI2 项目。我正在制作一个自定义方法来返回自定义 HttpStatusCode 以进行错误处理。

这是我的代码

    public IHttpActionResult GetError(int errCode) {
        int ErrCode = errCode * -1;
        ResourceManager ResourceManager = new ResourceManager("PIJ.API.OWIN.Properties.Resources", Assembly.GetExecutingAssembly());
        string ErrorMessage = ResourceManager.GetString("_" + ErrCode.ToString());

        return Content((HttpStatusCode)ErrCode, new HttpError(ErrorMessage));
    }

我现在的输出是这样的 Output Screenshot

我的问题是。 是否可以只返回 HttpStatusCode,而不返回错误消息?

Desired Output

非常感谢。

【问题讨论】:

  • 你应该发布代码而不是截图
  • @Prima,欢迎来到 Stack Overflow!请在您的问题正文中以纯文本的形式发布代码。将其添加为图像使人们很难将您的代码调整为答案,您无法复制粘贴它,并且它对那些依赖屏幕阅读器的人充满敌意
  • 感谢您的建议。抱歉,这是我第一次提问

标签: c# error-handling asp.net-web-api2


【解决方案1】:

您可以将StatusCodeResult 与所需的HttpStatusCode 返回。这可以使用ApiControllerStatusCode方法来完成

public IHttpActionResult Test()
{
    return StatusCode(HttpStatusCode.BadRequest);
}

【讨论】:

  • 是否可以返回自定义状态码? ..例如我想返回错误 600
  • 是的,你可以这样做StatusCode((HttpStatusCode)600);
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2015-09-21
  • 2011-04-27
  • 2018-09-02
  • 2021-09-13
相关资源
最近更新 更多