码迷,mamicode.com
首页 > Windows程序 > 详细

【原创】.NET Web API之filter ActionFilterAttribute 过滤器使用

时间:2015-09-02 10:38:39      阅读:646      评论:0      收藏:0      [点我收藏+]

标签:

1、在filter类里面引用,与MVC里面的不同

using System.Web.Http.Controllers;
using System.Web.Http.Filters;

2、filter类里面实现的代码,返回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、在Controller里面Action里面使用,和MVC一样

// GET api/values
        [FilterAttribute1]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

 

【原创】.NET Web API之filter ActionFilterAttribute 过滤器使用

标签:

原文地址:http://www.cnblogs.com/crazybottle/p/4777805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!