Last active
June 3, 2023 07:12
-
-
Save jhlee8804/8967c469bf7e802da67a219df413a2ff to your computer and use it in GitHub Desktop.
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.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); | |
} | |
} | |
} | |
} | |
} |
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
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