【问题标题】:ASP.NET Core return custom response when method is not allowed不允许使用方法时,ASP.NET Core 返回自定义响应
【发布时间】:2017-03-06 11:54:28
【问题描述】:

我正在使用 ASP.NET Core 构建 REST 服务

如果用户尝试使用不受支持的方法请求端点,我需要返回自定义响应代码。 例如端点 localhost/api/test 仅支持 GET 方法,但用户使用 POST 方法请求它。我需要返回 404 响应和自定义正文。

如何用 ASP.NET Core 做到这一点?


更新:

可能我的问题表述不正确。
如果不允许某个方法,我需要 ASP Core 返回 405 响应代码和自定义 JSON 正文。 这应该是标准行为,但尚未实现(根据此issue) 所以我正在寻找解决方法来返回 405 响应代码,但 ASP Core 不支持它。

【问题讨论】:

  • 你问的是 Asp.Net Core 吗?如果是,请改进您的问题(ASP 核心)
  • 你本来可以那样做的!
  • 我想捕获仅在不允许使用方法时引发的 404 错误并返回适当的消息作为响应。理想情况下,当仅允许 GET 方法时尝试使用 POST 方法时,我想返回 405 响应“方法不允许”。

标签: c# rest asp.net-core


【解决方案1】:

在控制器方法级别上,这可能会指导您。您使用首选状态代码和消息创建 HttpResonseMessage。注意:如果你想要像 302 这样的状态,那么你还需要填写位置标题。

 if (Request.Method.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
 {
                IHttpActionResult response;
                HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.NotFound);
                responseMsg.Content = new StringContent("Method doesn't support POST or whatever", System.Text.Encoding.UTF8, "text/html");

                response = ResponseMessage(responseMsg);
                return response;
 }

假设您在控制器方法中添加了一个自定义标头,以将其与框架响应区分开来。 在 webapi.config 中注册一个 CustomMessageHandler。

config.MessageHandlers.Add(new CustomMessageHandler());

//像下面一样定义CustomMessageHandler并覆盖SendAsync

 public class CustomMessageHandler: DelegatingHandler
        {
       protected override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var reasonInvalid = String.Empty;

                var res= base.SendAsync(request, cancellationToken);
                if (res.Result.StatusCode == HttpStatusCode.NotFound || res.Result.StatusCode == HttpStatusCode.MethodNotAllowed)
                {
                    if(!res.Result.Headers.Contains("CustomHeaderforIntentional404"))
                    {

                         res.Result.StatusCode = HttpStatusCode.MethodNotAllowed;
                         res.Result.Content = new StringContent("Method doesn't support this method CUSTOM MESSAGE", System.Text.Encoding.UTF8, "text/html");
                         return res;

                    }
                }
                return res;



                }
    }

【讨论】:

  • 如果控制器的方法故意返回404响应怎么办?如何区分有意响应和框架响应?
  • 您可以随时在“有意响应”中添加额外的标题来区分它们。
【解决方案2】:

根据官方文档...

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling

app.UseStatusCodePages();

// app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
// app.UseStatusCodePages("text/plain", "Response, status code: {0}");
// app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
// app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
// app.UseStatusCodePages(builder => builder.UseWelcomePage());
// app.UseStatusCodePagesWithReExecute("/errors/{0}");

...类似的东西应该可以工作。

【讨论】:

猜你喜欢
  • 2019-07-28
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 2019-05-18
  • 2019-09-22
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多