【问题标题】:How to get the Message on StatusCodes.Status204NoContent如何获取有关 StatusCodes.Status204NoContent 的消息
【发布时间】:2021-10-19 15:11:50
【问题描述】:

我的控制器中有这个:

[

HttpPost]
        public async Task<ActionResult> UpdateCalendarEntry(CalendarEntry model)
        {
            try
            {
                model.LabelColor = "blue";
                var result = await repo.AddCalendarEntry(model);
                if(result == null)
                {
                    return StatusCode(StatusCodes.Status204NoContent, "Cannot Do It!");
                }
                return apiResult.Send200(result);
            }
            catch (Exception ex)
            {

                return apiResult.Send400(ex.Message);
            }
        }

我在 Blazor WASM 中的服务中得到响应,如下所示:

using var response = await httpClient.SendAsync(request);
            var content = await response.Content.ReadAsStringAsync();

            // auto logout on 401 response
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                navigationManager.NavigateTo("login");
                return default;
            }

            if(response.StatusCode == HttpStatusCode.BadRequest)
            {
                await helperService.InvokeAlert("Bad Request", $@"{response.ReasonPhrase}", true);
            }

            if(response.StatusCode == HttpStatusCode.NoContent)
            {
                var x = response.Content.ReadAsStringAsync();
                await helperService.InvokeAlert("Bad Request", $@"{response.ReasonPhrase}", true);
            }

            // throw exception on error response
            if (!response.IsSuccessStatusCode)
            {
                //var error = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
                //throw new (error["message"]);

                return default;
                //throw new ApplicationException
                //    ($"The response from the server was not successful: {response.ReasonPhrase}, " +
                //    $"Message: {content}");
            }

我需要从控制器获得关于“无内容”消息“不能这样做!”的回复。我正在尝试 ReasonPhrase,但我不知道如何将错误放在那里。

【问题讨论】:

  • 您可以使用ObjectResult手动设置状态码
  • @AndriyShevchenko,先生,你能告诉我怎么做吗?
  • “204 响应被标头字段之后的第一个空行终止,因为它不能包含消息正文。”根据this
  • 204 是一个成功指标,没有返回任何附加信息,因此 OP 在这里尝试使用它的方式与协议的定义方式无关。 -- 或许他应该返回一个

标签: c# asp.net-core blazor-webassembly


【解决方案1】:

当您重新调整 NoContext 响应时,您无法返回任何值。这是我看到的将您的消息添加到响应标头的唯一方法。这段代码是用VS测试的

....
 if(response.StatusCode == HttpStatusCode.NoContent)
 {
   var reason= response.Headers.FirstOrDefault(h=> h.Key=="Reason");
   if(reason!=null)
    await helperService.InvokeAlert("Bad Request", $@"{reason.Value}", true);
 }
 .....

动作

HttpPost]
 public async Task<ActionResult> UpdateCalendarEntry(CalendarEntry model)
 {
            .....
  if(result == null)
  {
 HttpContext.Response.Headers.Add("Reason", "Cannot Do It!");
return NoContent();
  }
}

【讨论】:

    【解决方案2】:

    警告,未经测试。

    [HttpPost]
    public async Task<ActionResult> UpdateCalendarEntry(CalendarEntry model)
    {
          try
          {
                model.LabelColor = "blue";
                var result = await repo.AddCalendarEntry(model);
                if(result == null)
                {
                     return new ObjectResult("Cannot Do It!")
                     {
                          StatusCode = HttpStatusCode.NoContent
                     };
                }
                return apiResult.Send200(result);
          } 
          catch (Exception ex)
          {
                return apiResult.Send400(ex.Message);
          }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-25
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 2019-12-12
      相关资源
      最近更新 更多