[Original]. NET Web API filter ActionFilterAttribute filter, filter
1. Reference in the filter class, which is different from that in MVC.
using System.Web.Http.Controllers;using System.Web.Http.Filters;
2. The Code implemented in the filter class returns json
public class FilterAttribute1 : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext filterContext) { var httpContext = (HttpContextWrapper)filterContext.Request.Properties["MS_HttpContext"]; string ID = httpContext.Request["ID"]; if (!string.IsNullOrEmpty(ID)) { string jsonString = "{\"Status\":0,\"msg\":\"hello\"}"; HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(jsonString, Encoding.GetEncoding("UTF-8"), "application/json") }; filterContext.Response = result; } base.OnActionExecuting(filterContext); } }
3. Use the Action in the Controller, which is the same as MVC.
// GET api/values [FilterAttribute1] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }