【问题标题】:How to throw error (Bad Request) in void method in Web API如何在 Web API 的 void 方法中抛出错误(错误请求)
【发布时间】:2022-12-11 07:16:38
【问题描述】:

如何在 Web API 的 void 方法中抛出错误(错误请求)

public async Task UpdateRecord([FromBody] UpdateRecord model)
        {
            try
            {
                await _recordService.UpdateRecord(model);
            }
            catch (Exception ex)
            {
                var message = new NetHttp.HttpResponseMessage(HttpStatusCode.BadRequest);
                message.Content = new NetHttp.StringContent(ex.Message);
                throw new WebHttp.HttpResponseException(message);
            }
        }

大摇大摆地显示为 500。但我已经提到 400 - Bad Request

【问题讨论】:

    标签: c# asp.net-web-api webapi http-status-code-400 httpresponsemessage


    【解决方案1】:

    由于您抛出异常,因此它将始终为 500(如果您没有在其他任何地方捕获它)。

    如果你想要一个错误的请求,那么

    public async Task<IHttpActionResult> UpdateRecord([FromBody] UpdateRecord model)
            {
                try
                {
                    await _recordService.UpdateRecord(model);
                }
                catch (Exception ex)
                {
                            return ResponseMessage(
                Request.CreateResponse(
                    HttpStatusCode.BadRequest, 
                    validationErrors));
                }
    return Ok(returnData);
            }
    

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2020-11-13
      • 2017-02-10
      相关资源
      最近更新 更多