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'.
これは私のコードです:
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 を返す別の方法はありますか?