Skip to content

Instantly share code, notes, and snippets.

@harboe
Created June 7, 2013 18:20
Show Gist options
  • Save harboe/5731285 to your computer and use it in GitHub Desktop.
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
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