Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Creamos el filtro
- public class EnteroFilter : System.Web.Http.Filters.ActionFilterAttribute
- {
- public override void OnActionExecuting(HttpActionContext filterContext)
- {
- if (!filterContext.ModelState.IsValid)
- {
- if (filterContext.ActionArguments.TryGetValue("id", out object value))
- {
- if (null == value)
- {
- filterContext.Response =
- filterContext.Request
- .CreateResponse(
- HttpStatusCode.BadRequest,
- new { Code = HttpStatusCode.BadRequest, reason = "data invalida para param Id" });
- }
- }
- //o bien para obtener todos los errores
- var errores = filterContext
- .ModelState
- .Values
- .Select((x, index) =>
- new
- {
- key = filterContext.ModelState.Keys.ElementAt(index),
- error = x.Errors[index].Exception.InnerException.Message //validar que tenga innerException
- });
- }
- }
- }
- //Registrar el filtro
- //en WebApiConfig.cs
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- // Web API configuration and services
- //...
- }
- internal static void RegisterGlobalFilters(HttpFilterCollection filters)
- {
- filters.Add(new EnteroFilter());
- }
- }
- //en global.asax
- public class WebApiApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- //...
- WebApiConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
- //...
- }
- }
- //Usar el filtro
- public class ValuesController : ApiController
- {
- // GET api/values/5
- [EnteroFilter]
- public string Get(int id)
- {
- return "value";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment