Skip to content

Instantly share code, notes, and snippets.

@roseeng
Created September 9, 2020 14:54
Show Gist options
  • Save roseeng/c9a2362f13a34acab0ff3aff14b8e864 to your computer and use it in GitHub Desktop.
Save roseeng/c9a2362f13a34acab0ff3aff14b8e864 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentValidation;
using FluentValidation.AspNetCore;
using FluentValidation.Results;
using Microsoft.AspNetCore.Mvc;
namespace WebApiTest
{
/// <summary>
/// This class is intended to be used in WebApi projects, making it possible to
/// have different validations on POST (where you don't want to send an Id) and other calls.
/// It can only be used where we have an http context, and the NotEmptyOnUpdate test can only be used
/// in an HttpAbstractValidator.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class HttpAbstractValidator<T> : AbstractValidator<T>, IValidatorInterceptor
{
public ValidationResult AfterMvcValidation(ControllerContext controllerContext, IValidationContext commonContext, ValidationResult result)
{
return result;
}
public IValidationContext BeforeMvcValidation(ControllerContext controllerContext, IValidationContext commonContext)
{
var a = controllerContext?.HttpContext?.Request?.Method;
commonContext.RootContextData["HttpMethod"] = a;
return commonContext;
}
}
public static class ExtensionMethods
{
public static IRuleBuilderOptions<T, TElement> NotEmptyOnUpdate<T, TElement>(this IRuleBuilder<T, TElement> ruleBuilder)
{
return ruleBuilder.Must((rootObject, field, context) => {
if (context.ParentContext.RootContextData.ContainsKey("HttpMethod") == false)
throw new ValidationException("NotEmptyOnUpdate validation can only be used by a HttpAbstractValdator");
string method = context.ParentContext.RootContextData["HttpMethod"] as string;
context.MessageFormatter.AppendArgument("HttpMethod", method);
if (method == "POST")
return true; // Bypass check
else
return !string.IsNullOrEmpty(field as string);
})
.WithMessage("{PropertyName} must not be empty in a {HttpMethod} request.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment