webapi 如何添加过滤器,并在过滤器中获取客户端传过来的参数

给控制器下的行为添加过滤器

新建一个类ActionFilter 名字随便取,然后让他集成ActionFilterAttribute并实现虚方法,虚方法有好几种,我使用的是进入方法之前的,如需了解更多虚方法,点击这里

public class ActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        string userid = System.Web.HttpContext.Current.Request.Params["UserID"].ToString();
        int id;
        if (int.TryParse(userid, out id))
        {
            //此处执行你想要的操作
        }
        base.OnActionExecuting(actionContext);
    }
}

上边是个单个行为添加过滤器,下边是给整个控制器添加过滤器

public class MyFilter : ActionFilter
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        string userid = System.Web.HttpContext.Current.Request.Params["UserID"].ToString();
        base.OnActionExecuting(actionContext);
    }
}

 记一下,webapi发布之后可能遇到的问题:

找不到方法:“System.Net.Http.HttpRequestMessage System.Web.Http.Controllers.HttpActionContext.get_Request()

解决办法:

在项目webconfig中添加

  <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>

  

posted on 2017-09-19 22:11  有梦想的咸鱼¥  阅读(392)  评论(0编辑  收藏  举报

导航