gpt4 book ai didi

c# - 如何自定义 415 状态码的错误信息?

转载 作者:行者123 更新时间:2023-11-30 17:33:49 25 4
gpt4 key购买 nike

我们已将媒体类型限制为“application/json”。因此,如果请求 header 包含“Content-Type:text/plain”,它会响应以下错误消息和状态代码 415。这种行为是预期的,但我想发送状态代码为 415 的空响应。我们如何在 .网络 API?

{
"message": "The request entity's media type 'text/plain' is not supported for this resource.",
"exceptionMessage": "No MediaTypeFormatter is available to read an object of type 'MyModel' from content with media type 'text/plain'.",
"exceptionType": "System.Net.Http.UnsupportedMediaTypeException",
"stackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}

最佳答案

您可以创建消息处理程序,它将在管道早期检查请求的内容类型,如果不支持请求内容类型,则返回 415 状态代码和空主体:

public class UnsupportedContentTypeHandler : DelegatingHandler
{
private readonly MediaTypeHeaderValue[] supportedContentTypes =
{
new MediaTypeHeaderValue("application/json")
};

protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var contentType = request.Content.Headers.ContentType;
if (contentType == null || !supportedContentTypes.Contains(contentType))
return request.CreateResponse(HttpStatusCode.UnsupportedMediaType);

return await base.SendAsync(request, cancellationToken);
}
}

将此消息处理程序添加到 http 配置的消息处理程序(在 WebApiConfig):

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

对于所有未提供内容类型或内容类型不受支持的请求,您将得到空响应。

请注意,您可以从全局配置中获取支持的媒体类型(以避免重复此数据):

public UnsupportedContentTypeHandler()
{
supportedContentTypes = GlobalConfiguration.Configuration.Formatters
.SelectMany(f => f.SupportedMediaTypes).ToArray();
}

关于c# - 如何自定义 415 状态码的错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43241443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com