Skip to content

Instantly share code, notes, and snippets.

@GeorgDangl
Created December 19, 2016 19:57
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 GeorgDangl/ac93bb61653cb6761d3ad2c2fd695b31 to your computer and use it in GitHub Desktop.
Save GeorgDangl/ac93bb61653cb6761d3ad2c2fd695b31 to your computer and use it in GitHub Desktop.
Validation filter to automatically return BadRequest respones for invalid models and IsEqualToAttribute for comparing Password and ConfirmPasswords in models
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Filters
{
public class ApiModelStateValidationFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid && context.HttpContext.Request.Path.StartsWithSegments("/Api", StringComparison.OrdinalIgnoreCase))
{
var apiErrorResult = new ApiResponse<object>(new ApiError(context.ModelState));
context.Result = new BadRequestObjectResult(apiErrorResult);
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Not doing anything after the action has executed
}
}
}
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace Attributes
{
public class IsEqualToAttribute : ValidationAttribute
{
public IsEqualToAttribute(string compareTo)
{
_compareTo = compareTo;
}
public override bool RequiresValidationContext => true;
private readonly string _compareTo;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var validationPartner = validationContext.ObjectInstance.GetType().GetTypeInfo().GetProperty(_compareTo).GetValue(validationContext.ObjectInstance);
return validationPartner?.Equals(value) == true
? ValidationResult.Success
: new ValidationResult($"The property is expected to be equal to \"{_compareTo}\".");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment