如何获取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}");
}

我需要得到控制器的回复"No Content"我做不到!"我正在尝试使用ReasonPhrase,但我不知道如何将错误放在那里。

当你返回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();
}
}

警告,未测试。

[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);
}
}

相关内容

  • 没有找到相关文章

最新更新