DnTo

Filter in WebApi

May 24th, 2021 (edited)
1,150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | None | 0 0
  1. //Creamos el filtro
  2.     public class EnteroFilter : System.Web.Http.Filters.ActionFilterAttribute
  3.     {
  4.         public override void OnActionExecuting(HttpActionContext filterContext)
  5.         {
  6.             if (!filterContext.ModelState.IsValid)
  7.             {
  8.                 if (filterContext.ActionArguments.TryGetValue("id", out object value))
  9.                 {
  10.                     if (null == value)
  11.                     {
  12.                         filterContext.Response =
  13.                             filterContext.Request
  14.                             .CreateResponse(
  15.                                 HttpStatusCode.BadRequest,
  16.                             new { Code = HttpStatusCode.BadRequest, reason = "data invalida para param Id" });
  17.                     }
  18.                 }
  19.                 //o bien para obtener todos los errores
  20.                 var errores = filterContext
  21.                     .ModelState
  22.                     .Values
  23.                     .Select((x, index) =>
  24.                     new
  25.                     {
  26.                         key = filterContext.ModelState.Keys.ElementAt(index),
  27.                         error = x.Errors[index].Exception.InnerException.Message //validar que tenga innerException
  28.                     });
  29.             }
  30.         }
  31.     }
  32.  
  33.  
  34.  
  35. //Registrar el filtro
  36. //en WebApiConfig.cs
  37.   public static class WebApiConfig
  38.     {
  39.         public static void Register(HttpConfiguration config)
  40.         {
  41.             // Web API configuration and services
  42.             //...
  43.         }
  44.  
  45.         internal static void RegisterGlobalFilters(HttpFilterCollection filters)
  46.         {
  47.                filters.Add(new EnteroFilter());
  48.         }
  49.     }
  50. //en global.asax
  51. public class WebApiApplication : System.Web.HttpApplication
  52.     {
  53.         protected void Application_Start()
  54.         {
  55.         //...
  56.             WebApiConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
  57.         //...
  58.  
  59.          
  60.         }
  61.     }
  62.  
  63. //Usar el filtro
  64.  public class ValuesController : ApiController
  65.     {
  66.         // GET api/values/5
  67.         [EnteroFilter]
  68.         public string Get(int id)
  69.         {
  70.             return "value";
  71.         }
  72.     }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment