gpt4 book ai didi

c# - 验证请求内容类型

转载 作者:太空狗 更新时间:2023-10-29 23:31:49 26 4
gpt4 key购买 nike

我正在尝试验证 POST、PUT 和 PATCH 请求中 Content-Type 的值,但当前代码仅在我忘记内容类型子句或使用如下内容类型时有效:“Content -类型:Foo”。
当我发送“Content-Type: text/css”时,我得到了这个:

500 Internal Server Error
No MediaTypeFormatter is available to read an object of type 'MyClassDto' from content with media type 'text/css'.

这是我的代码:

public class ContentTypeFilter : IActionFilter
{
private readonly List<MediaTypeHeaderValue> _suport;

/// <summary />
public ContentTypeFilterAttribute()
{
_suport = new List<MediaTypeHeaderValue>();

foreach (var formatter in GlobalConfiguration.Configuration.Formatters.ToArray())
{
_suport.AddRange(formatter.SupportedMediaTypes);
}
}

public bool AllowMultiple { get { return false; } }

public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
var metodos = new List<string> { "POST", "PUT", "PATCH" };

if (actionContext.Request.Content != null)
{
if (metodos.Contains(actionContext.Request.Method.Method.ToUpperInvariant()))
{
MediaTypeHeaderValue contentType = actionContext.Request.Content.Headers.ContentType;

if (contentType == null || !_suport.Any(x => x.MediaType.Equals(contentType.MediaType)))
{
return CreateResponse(actionContext.Request, "Invalid Content-Type");
}
}
}

return continuation();
}

private static Task<HttpResponseMessage> CreateResponse(HttpRequestMessage request, string mensagem)
{
var tsc = new TaskCompletionSource<HttpResponseMessage>();
var response = request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
response.ReasonPhrase = mensagem;
response.Content = new StringContent(mensagem);
tsc.SetResult(response);

return tsc.Task;
}

如果内容不是 XML 或 JSON,是否有另一种方法来验证内容类型并返回错误 415?

最佳答案

我找到了一个很好的解决方案 here .

通过一些改变来获得我想要的:

public class ContentTypeFilter : DelegatingHandler
{
private readonly List<MediaTypeHeaderValue> _suport;

/// <summary />
public ContentTypeFilter()
{
_suport = new List<MediaTypeHeaderValue>();

foreach (var formatter in GlobalConfiguration.Configuration.Formatters.ToArray())
{
_suport.AddRange(formatter.SupportedMediaTypes);
}
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var metodos = new List<string> { "POST", "PUT", "PATCH" };

if (request.Content != null)
{
if (metodos.Contains(request.Method.Method.ToUpperInvariant()))
{
MediaTypeHeaderValue contentType = request.Content.Headers.ContentType;

// Nas configurações não possui o Charset aceito.
if (contentType == null || !_suport.Any(x => x.MediaType.Equals(contentType.MediaType)))
{
return Task<HttpResponseMessage>.Factory.StartNew(() => CreateResponse(request, "Suported content-types: " + string.Join(", ", _suport.Select(x => x.ToString()))));
}
}
}
return base.SendAsync(request, cancellationToken);
}

private static HttpResponseMessage CreateResponse(HttpRequestMessage request, string mensagem)
{
var response = request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
response.ReasonPhrase = mensagem;
response.Content = new StringContent(mensagem);

return response;
}
}

关于c# - 验证请求内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19100131/

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