web api添加拦截器


实现思路

1.标识控制器有拦截特性;

2.控制器拦截处理;

代码实现

1.标识控制器有拦截特性,代码:

[MyFilter]
public string PostFindUser([FromBody]Userinfo user)
{
    return string.Format("{0}是好人~", user.Name);
}

2.控制器拦截处理,代码:

public class MyFilter : ActionFilterAttribute
{

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        base.OnActionExecuting(actionContext);
        //获取请求参数
        WebApiTest.Controllers.Userinfo user = (WebApiTest.Controllers.Userinfo)actionContext.ActionArguments["user"];

        //TODO:业务判断
        if (user.Name == "小明") //请求终止,进行调整或者内容输出
        {
            //HttpContext.Current.Response.Redirect("~/home/index");
            HttpContext.Current.Response.Write("{\"id\":1,\"name\":\"小明\"}");
            //创建响应对象,初始化为成功,没有指定的话本次请求将不会被拦截
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        }
    }

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM