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

3
我正在使用ASP.NET Core构建REST服务。
如果用户尝试使用不支持的方法请求端点,我需要返回自定义响应代码。例如,端点localhost/api/test仅支持GET方法,但用户使用POST方法请求它。我需要返回404响应和自定义主体。
如何在ASP.NET Core中实现这一点?

更新:

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


1
这个有帮助吗?http://www.talkingdotnet.com/handle-404-error-asp-net-core-mvc-6/ - Maarten
你是在询问 Asp.Net Core 吗?如果是的话,请改进你的问题(ASP Core)。 - ravindra
你本来可以做到的! - War
我想捕获仅在不允许使用方法时引发的404错误,并在响应中返回适当的消息。理想情况下,当尝试使用POST方法而只允许使用GET方法时,我希望返回405响应“方法不允许”。 - Valentine
2个回答

1

在控制器方法级别,可能会有所指导。您可以创建一个HttpResponseMessage,其中包含您喜欢的状态代码和消息。注意:如果您想要类似于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响应怎么办?如何区分故意响应和框架响应? - Valentine
你可以在“有意义的响应(Intentional response)”中添加额外的标头来区分它们。 - SSA

-1

根据官方文档...

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

...这样应该可以工作。


当我们拥有关于错误处理的官方文档时,不要将任何人引导到不受信任和过时的文章...https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling - J. Doe
好的,没问题,已经更改了! - War

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接