title: Validating Request Content-Type
body: <p>I'm trying to validate the value of Content-Type in POST, PUT and PATCH requests, but the current code is only working when I forget the content-type clause or when I use a content-type like: "Content-Type: Foo".
  <br>When I send "Content-Type: text/css" I get this:</p>
  
  <pre><code>500 Internal Server Error
  No MediaTypeFormatter is available to read an object of type 'MyClassDto' from content with media type 'text/css'.
  </code></pre>
  
  <p>This is my code:</p>
  
  <pre><code>public class ContentTypeFilter : IActionFilter
  {
      private readonly List&lt;MediaTypeHeaderValue&gt; _suport;
  
      /// &lt;summary /&gt;
      public ContentTypeFilterAttribute()
      {
          _suport = new List&lt;MediaTypeHeaderValue&gt;();
  
          foreach (var formatter in GlobalConfiguration.Configuration.Formatters.ToArray())
          {
              _suport.AddRange(formatter.SupportedMediaTypes);
          }
      }
  
      public bool AllowMultiple { get { return false; } }
  
      public Task&lt;HttpResponseMessage&gt; ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func&lt;Task&lt;HttpResponseMessage&gt;&gt; continuation)
      {
          var metodos = new List&lt;string&gt; { "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 =&gt; x.MediaType.Equals(contentType.MediaType)))
                  {
                      return CreateResponse(actionContext.Request, "Invalid Content-Type");
                  }
              }
          }
  
          return continuation();
      }
  
      private static Task&lt;HttpResponseMessage&gt; CreateResponse(HttpRequestMessage request, string mensagem)
      {
          var tsc = new TaskCompletionSource&lt;HttpResponseMessage&gt;();
          var response = request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
          response.ReasonPhrase = mensagem;
          response.Content = new StringContent(mensagem);
          tsc.SetResult(response);
  
          return tsc.Task;
      }
  </code></pre>
  
  <p>Is there another way to validate content-type and return error 415 if the content isn't XML or JSON?</p>