【发布时间】:2020-09-29 22:55:07
【问题描述】:
我正在将一个 API 从 .NET 移植到 .NET Core。对于任务,每个响应都需要相同。 如果我在仅“GET”端点上尝试“PUT”请求,旧 API 在 Postman 中返回以下状态码 405:
{
"Message": "The requested resource does not support http method 'PUT'."}
.NET Core 默认返回 405 的空正文。
我的问题是如何在 .NET CORE 中模拟第一个示例的响应正文。
我目前的尝试使我创建了一个在app.UseRouting(); 之前添加的中间件。
中间件如下所示: public class MethodNotAllowedMiddleware
{
私有 RequestDelegate _next;
public MethodNotAllowedMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
await _next(context);
if(context.Response.StatusCode == (int)HttpStatusCode.MethodNotAllowed)
{
await context.Response.WriteAsync("The requested resource does not support http method 'PUT'.");//This will NOT be hardcoded string
}
}
}
但是响应正文是纯字符串,而不是 JSON 格式。 如何使用适当的类而不是硬编码字符串来构建响应?我认为这是一个非常 hacky 的解决方案,应该有一种更优雅的方式来解决我所缺少的问题。
【问题讨论】:
标签: api asp.net-core asp.net-core-webapi