首页 > 解决方案 > 如何获取有关 StatusCodes.Status204NoContent 的消息

问题描述

我的控制器中有这个:

[

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,但我不知道如何将错误放在那里。

标签: c#asp.net-coreblazor-webassembly

解决方案


重新调整 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();
  }
}

推荐阅读