Skip to content

Instantly share code, notes, and snippets.

@johnib
Created November 22, 2020 10:13
Show Gist options
  • Save johnib/bd7eceb09a197cc25c12983db25f2e4d to your computer and use it in GitHub Desktop.
Save johnib/bd7eceb09a197cc25c12983db25f2e4d to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace SchedulerApi.Filters
{
/// <inheritdoc />
/// <summary>
/// This attribute takes care of returning 400 Bad Request when user input is not valid
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ValidateRequestBodyAttribute : TypeFilterAttribute
{
public ValidateRequestBodyAttribute() : base(typeof(ValidateRequestBodyAttributeImpl))
{
}
}
public class ValidateRequestBodyAttributeImpl : IAsyncActionFilter
{
private readonly ILoggerFactory _loggerFactory;
public ValidateRequestBodyAttributeImpl(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
BadRequestObjectResult result = new BadRequestObjectResult(context.ModelState);
context.Result = result;
ILogger logger = _loggerFactory.CreateLogger("ModelState");
logger.LogWarning(
"ModelState validation failure: {principal}; {method}: {path}; {statusCode}; {result}; {actionArguments}",
context.HttpContext.User.Identity.Name, context.HttpContext.Request.Method,
context.HttpContext.Request.Path, result.StatusCode,
JsonConvert.SerializeObject(result.Value),
JsonConvert.SerializeObject(context.ActionArguments));
}
else
{
await next();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment