Created
August 23, 2017 15:25
-
-
Save yuv4ik/2bfc53bdfa22926fb016b63100e38596 to your computer and use it in GitHub Desktop.
Web.API 2 model state validation action filter
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 System.Net; | |
using System.Net.Http; | |
using System.Web.Http.Controllers; | |
using System.Web.Http.Filters; | |
namespace MyAwesomeWebApi.ActionFilters | |
{ | |
/// <summary> | |
/// Returns 400 if the ModelState is invalid. | |
/// </summary> | |
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] | |
public class ValidateModelAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuting(HttpActionContext actionContext) | |
{ | |
if (actionContext.ModelState.IsValid) | |
return; | |
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
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using System.Web.Http; | |
using System.Web.Http.Description; | |
using System.ComponentModel.DataAnnotations; | |
namespace MyAwesomeWebApi.Controllers | |
{ | |
public class ValuesController : ApiController | |
{ | |
[ValidateModel] | |
public IHttpActionResult Post(MyModel model) | |
{ | |
var valService = new ValService(); | |
var result = valService.Create(model); | |
return Created($"api/values/{result.Id}", result); | |
} | |
} | |
public class MyModel | |
{ | |
[Required] | |
public int Id { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment