Created
November 22, 2020 10:13
-
-
Save johnib/bd7eceb09a197cc25c12983db25f2e4d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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