简体   繁体   English

ASP.NET Core在不允许方法时返回自定义响应

[英]ASP.NET Core return custom response when method is not allowed

I'm using ASP.NET Core for building REST service 我正在使用ASP.NET Core来构建REST服务

I need to return custom response code if user tries to request an endpoint with unsupported method. 如果用户尝试使用不支持的方法请求端点,我需要返回自定义响应代码。 For example endpoint localhost/api/test supports GET method only, but user requests it with POST method. 例如,端点localhost / api / test仅支持GET方法,但用户使用POST方法请求它。 I need to return 404 response and custom body. 我需要返回404响应和自定义正文。

How to do this with ASP.NET Core? 如何使用ASP.NET Core执行此操作?


UPD: UPD:

Possibly I formulated my question incorrectly. 可能我错误地提出了我的问题。
I need ASP Core return 405 response code with custom JSON body in case if a method is not allowed. 如果不允许方法,我需要ASP Core返回405响应代码和自定义JSON主体。 This should be a standard behavior, but not implemented yet (according to this issue ) So I'm looking to workaround to return 405 response code nevertheless ASP Core does not support it out of box. 这应该是一个标准的行为,但尚未实现(根据这个问题 )所以我希望解决方法返回405响应代码然而ASP Core不支持它开箱即用。

On a controller method level, probably this will guide you. 在控制器方法级别,这可能会指导您。 You create a HttpResonseMessage, with your preferred status code and message. 您可以使用首选的状态代码和消息创建HttpResonseMessage。 Note: if you want status like 302 then you also need to fill location header. 注意:如果您想要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;
 }

Assuming you add a custom header in your controller method, to differencitate it from framework response. 假设您在控制器方法中添加自定义标头,以将其与框架响应区分开来。 In webapi.config register a CustomMessageHandler. 在webapi.config中注册一个CustomMessageHandler。

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

//Define CustomMessageHandler like below and overide SendAsync //如下所示定义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;



                }
    }

as per the official docs ... 根据官方文件......

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling 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}");

... something like that should work. ......这样的事情应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM