Skip to content

Instantly share code, notes, and snippets.

@jhlee8804
Last active June 3, 2023 07:12
Show Gist options
  • Save jhlee8804/8967c469bf7e802da67a219df413a2ff to your computer and use it in GitHub Desktop.
Save jhlee8804/8967c469bf7e802da67a219df413a2ff to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
namespace MyApi.Filters
{
/// <summary>
/// <see cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api"/>
/// </summary>
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var nullable = actionContext.ActionArguments.FirstOrDefault(kv => kv.Value == null);
if (!nullable.Equals(default(KeyValuePair<string, object>)))
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, $"\"{nullable.Key}\" cannot be null");
return;
}
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ValidateModelAttribute());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment