Created
June 7, 2013 18:20
-
-
Save harboe/5731285 to your computer and use it in GitHub Desktop.
snippet from somewhere. An ActionFilter for return the corrent Html Repsonse Code for an invalid model state in ASP.NET WebApi
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.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Web.Http.Controllers; | |
using System.Web.Http.Filters; | |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] | |
public class ValidateModelStateAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuting(HttpActionContext actionContext) | |
{ | |
var modelState = actionContext.ModelState; | |
if (!modelState.IsValid) | |
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState); | |
//else if (IsFormBodyNull(actionContext)) | |
// actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request has no body content"); | |
} | |
private bool IsFormBodyNull(HttpActionContext actionContext) | |
{ | |
return actionContext.ActionDescriptor.GetParameters() | |
.Where(x => x.ParameterBinderAttribute != null && actionContext.ActionArguments[x.ParameterName] == null) | |
.FirstOrDefault() != null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment