[英]ASP.NET Core return custom response when method is not allowed
我正在使用ASP.NET Core來構建REST服務
如果用戶嘗試使用不支持的方法請求端點,我需要返回自定義響應代碼。 例如,端點localhost / api / test僅支持GET方法,但用戶使用POST方法請求它。 我需要返回404響應和自定義正文。
如何使用ASP.NET Core執行此操作?
可能我錯誤地提出了我的問題。
如果不允許方法,我需要ASP Core返回405響應代碼和自定義JSON主體。 這應該是一個標准的行為,但尚未實現(根據這個問題 )所以我希望解決方法返回405響應代碼然而ASP Core不支持它開箱即用。
在控制器方法級別,這可能會指導您。 您可以使用首選的狀態代碼和消息創建HttpResonseMessage。 注意:如果您想要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;
}
}
根據官方文件......
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}");
......這樣的事情應該有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.