Created
January 26, 2018 17:18
-
-
Save mstum/ad91752eab527934eb6a0688c54d12a0 to your computer and use it in GitHub Desktop.
ASP.net Core Filter to limit allowed Content-Types per method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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