Valentine
Valentine

Reputation: 516

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

I'm using ASP.NET Core for building REST service

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. I need to return 404 response and custom body.

How to do this with ASP.NET Core?


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. 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.

Upvotes: 3

Views: 7633

Answers (2)

SSA
SSA

Reputation: 5493

On a controller method level, probably this will guide you. You create a HttpResonseMessage, with your preferred status code and message. Note: if you want status like 302 then you also need to fill location header.

 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.

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

//Define CustomMessageHandler like below and overide 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;



                }
    }

Upvotes: 1

War
War

Reputation: 8628

as per the official docs ...

https://learn.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.

Upvotes: -1

Related Questions