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?
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.
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;
}
}
as per the official docs ...
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.