Skip to content

Instantly share code, notes, and snippets.

@mstum
Created January 26, 2018 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mstum/ad91752eab527934eb6a0688c54d12a0 to your computer and use it in GitHub Desktop.
Save mstum/ad91752eab527934eb6a0688c54d12a0 to your computer and use it in GitHub Desktop.
ASP.net Core Filter to limit allowed Content-Types per method.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Stuff.Web
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class LimitContentTypesFilterAttribute : Attribute, IResourceFilter
{
private readonly HashSet<string> _allowedContentTypes;
public LimitContentTypesFilterAttribute(params string[] allowedContentTypes)
{
if (allowedContentTypes == null || allowedContentTypes.Length == 0)
{
throw new ArgumentException(nameof(allowedContentTypes) + " must not be empty.");
}
_allowedContentTypes = new HashSet<string>(allowedContentTypes);
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
public void OnResourceExecuting(ResourceExecutingContext context)
{
var reqContentType = context?.HttpContext?.Request?.ContentType;
if (string.IsNullOrEmpty(reqContentType)
|| !_allowedContentTypes.Any(ct => string.Equals(ct, reqContentType, StringComparison.OrdinalIgnoreCase)))
{
context.Result = new StatusCodeResult(415);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment