Created
December 19, 2016 19:57
-
-
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
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 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 | |
} | |
} | |
} |
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 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