Skip to content

Instantly share code, notes, and snippets.

@hardboiled
Last active December 12, 2016 19:08
Show Gist options
  • Save hardboiled/72b70999f592356da257c6df2251bb03 to your computer and use it in GitHub Desktop.
Save hardboiled/72b70999f592356da257c6df2251bb03 to your computer and use it in GitHub Desktop.
namespace MyRestApi.Filters
{
public class ValidateStateAttribute : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
var dict = new List<object>();
//Loop through each "model"/"contract" attribute, and return the error with a 422 status with the error messages.
foreach (var entry in actionContext.ModelState.Where(x => x.Value.Errors.Count > 0))
{
dict.Add(new
{
PropertyName = Regex.Replace(entry.Key, @"^[^\.]+\.", ""),
ErrorMessage = entry.Value.Errors.FirstOrDefault().ErrorMessage
});
}
actionContext.Response = actionContext.Request.CreateResponse(
422, dict
);
}
}
}
}
namespace MyRestApi.Contracts
{
public enum EAddressType
{
Billing,
Shipping
}
//validations are defined directly on the objects, instead of in the controller
public class dtoAddress
{
public EAddressType addressType { get; set; }
[Required]
public String firstName { get; set; }
[Required]
public String lastName { get; set; }
[Required]
public String line1 { get; set; }
public String line2 { get; set; }
[Required]
public String city { get; set; }
[RegularExpression(@"^[a-zA-Z]{2}$", ErrorMessage="State must use two-character code (e.g. NY)")]
public String state { get; set; }
[RegularExpression(@"^\d{5}(?:-\d{4}|)$", ErrorMessage="Please use 5 digit zip code or 9 digit zip code with hyphen")]
public String zipCode { get; set; }
[RegularExpression(@"^\d{10}$", ErrorMessage = "Phone number must be 10 digits")]
public String phone { get; set; }
[RegularExpression(@"^.+@.+\..+$", ErrorMessage = "Invalid Email Address")]
public String email { get; set; }
}
}
//FilterConfig.cs
namespace MyRestApi.Config
{
public class FilterConfig
{
public static void RegisterGlobalFilters(HttpFilterCollection filters)
{
filters.Add(new Filters.ValidateStateAttribute());
}
}
}
//Register filter config globally
//Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters); //<-- filter registered here
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
//..
}
//AddressController.cs
namespace MyRestApi.Controllers
{
public class AddressController : ApiController
{
public HttpResponseMessage Post(dtoAddress address)
{
//code here. ActionFilter will handle validations for city/state/zip/etc. before this method is called.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment