当不允许使用方法时,ASP.NET Core返回自定义响应 [英] ASP.NET Core return custom response when method is not allowed

查看:296
本文介绍了当不允许使用方法时,ASP.NET Core返回自定义响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

How to do this with ASP.NET Core?

可能我提出的问题不正确.
如果不允许使用方法,我需要带有自定义JSON正文的ASP Core返回405响应代码. 这应该是标准行为,但尚未实现(根据此 issue ) 因此,我正在寻求一种变通办法以返回405响应代码,但是ASP 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.

推荐答案

在控制器方法级别,可能会为您提供指导.您使用您的首选状态代码和消息创建一个HttpResonseMessage.注意:如果您想要状态为302,则还需要填写位置标题.

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;
 }

假设您在控制器方法中添加了一个自定义标头,以区别于框架响应. 在webapi.config中注册CustomMessageHandler.

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());

//定义如下的CustomMessageHandler并覆盖SendAsync

//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;



                }
    }

这篇关于当不允许使用方法时,ASP.NET Core返回自定义响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆