web api添加攔截器

實現思路

1.標識控制器有攔截特性;

2.控制器攔截處理;

代碼實現

1.標識控制器有攔截特性,代碼:

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

2.控制器攔截處理,代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
        }
    }
 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章