【发布时间】: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