Custom Content Validation Filter?

I want to implement a special content validation filter so that I can create a custom error model in the 415 Unsupported Media Type.

Something like that:

public class ValidateContentTypeFilterAttribute : ActionFilterAttribute
{
    private const string JsonMimeType = "application/json";

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        string requestMethod = context.HttpContext.Request.Method.ToUpper();

        if (requestMethod == WebRequestMethods.Http.Post || requestMethod == WebRequestMethods.Http.Put)
        {
            if (request.ContentType != JsonMimeType)
            {
                // "Unsupported Media Type" HTTP result.
                context.Result = new HttpUnsupportedMediaTypeResult();
                return;
            }
        }
    }
}

The problem is that the MVC pipeline seems to “catch” unsupported or invalid Content-Type values ​​before executing any custom filters. Even the content type "application / xml" will be denied.

Where will it be set up?

My MVC configuration consists of nothing more than this:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            options.SerializerSettings.Converters.Add(new SquidJsonConverter());
        })
        .AddMvcOptions(options =>
        {
            options.Filters.Add(typeof(ValidateAntiForgeryTokenAttribute));
            options.Filters.Add(typeof(ValidateContentTypeFilterAttribute));
            options.Filters.Add(typeof(ValidateAcceptFilterAttribute));
            options.Filters.Add(typeof(ValidateModelFilterAttribute));
        });
    ...
}
+4
source share
1 answer

, .

"" :

  • OnAuthorization..
  • OnResourceExecuting..
  • ( , )
  • Action filters 'OnActionExecuting..

. :  

public class CustomResourceFilter : IResourceFilter
{
    private readonly string jsonMediaType = "application/json";

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }

    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        if (context.HttpContext.Request.Method == "PUT" || context.HttpContext.Request.Method == "POST")
        {
            if (!string.Equals(
                MediaTypeHeaderValue.Parse(context.HttpContext.Request.ContentType).MediaType,
                jsonMediaType,
                StringComparison.OrdinalIgnoreCase))
            {
                context.Result = new JsonResult(new { Error = "An error message here" }) { StatusCode = 415 };
            }
        }
    }
}

UnsupportedMediaTypeResult, .

:

  1. Action filters 'OnActionExecuted...
  2. "OnResultExecuting.. "
  3. "OnResultExecuted.. >
  4. OnResourceExecuted..

:

public class CustomResultFilter : ResultFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        var result = context.Result as UnsupportedMediaTypeResult;
        if (result != null)
        {
            context.Result = new JsonResult(new { Error = "An error message here" }) { StatusCode = 415 };
        }
    }
}
+5

All Articles