c# - 如何获取有关 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,但我不知道如何将错误放在那里。
解决方案
重新调整 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();
}
}
推荐阅读
- node.js - 在'package.json'的'dependencies'字段中添加'npm'有什么意义吗?
- azure - 天蓝色;从 Java 应用程序访问 Key Vault 的权限错误
- macos - Xcode Cocoa:无法读取 CFPrefsPlistSource<0x600002909f10> 中的值
- c++ - 如何只构建一个依赖目标?
- java - Intellij 的远程调试非常频繁地断开连接
- javascript - 仅在预加载器结束后加载 jquery 事件
- chisel - 分别编译模块和链接
- sql-server - 如何在 Python 中检查是否为 Azure SQL Server 启用了审核
- c - 二进制矩阵向量乘法的内在函数
- firebase - 如何将数据从 Mongo db 迁移到 Firestore?