验证请求内容类型

Ale*_*nzi 5 c# asp.net-web-api

我正在尝试在POST,PUT和PATCH请求中验证Content-Type的值,但是当我忘记content-type子句或使用内容类型时,当前代码才起作用:"Content-Type:富".
当我发送"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'.
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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;
    }
Run Code Online (Sandbox Code Playgroud)

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

小智 4

在这里找到了一个很好的解决方案。

\n\n

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

\n\n
public class ContentTypeFilter : DelegatingHandler\n{\n    private readonly List<MediaTypeHeaderValue> _suport;\n\n    /// <summary />\n    public ContentTypeFilter()\n    {\n        _suport = new List<MediaTypeHeaderValue>();\n\n        foreach (var formatter in GlobalConfiguration.Configuration.Formatters.ToArray())\n        {\n            _suport.AddRange(formatter.SupportedMediaTypes);\n        }\n    }\n\n    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n    {\n        var metodos = new List<string> { "POST", "PUT", "PATCH" };\n\n        if (request.Content != null)\n        {\n            if (metodos.Contains(request.Method.Method.ToUpperInvariant()))\n            {\n                MediaTypeHeaderValue contentType = request.Content.Headers.ContentType;\n\n                // Nas configura\xc3\xa7\xc3\xb5es n\xc3\xa3o possui o Charset aceito.\n                if (contentType == null || !_suport.Any(x => x.MediaType.Equals(contentType.MediaType)))\n                {\n                    return Task<HttpResponseMessage>.Factory.StartNew(() => CreateResponse(request, "Suported content-types: " + string.Join(", ", _suport.Select(x => x.ToString()))));\n                }\n            }\n        }\n        return base.SendAsync(request, cancellationToken);\n    }\n\n    private static HttpResponseMessage CreateResponse(HttpRequestMessage request, string mensagem)\n    {\n        var response = request.CreateResponse(HttpStatusCode.UnsupportedMediaType);\n        response.ReasonPhrase = mensagem;\n        response.Content = new StringContent(mensagem);\n\n        return response;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n