web api添加拦截器
生活随笔
收集整理的這篇文章主要介紹了
web api添加拦截器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
實現(xiàn)思路
1.標識控制器有攔截特性;
2.控制器攔截處理;
代碼實現(xiàn)
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);//獲取請求參數(shù)WebApiTest.Controllers.Userinfo user = (WebApiTest.Controllers.Userinfo)actionContext.ActionArguments["user"];//TODO:業(yè)務(wù)判斷if (user.Name == "小明") //請求終止,進行調(diào)整或者內(nèi)容輸出{//HttpContext.Current.Response.Redirect("~/home/index");HttpContext.Current.Response.Write("{\"id\":1,\"name\":\"小明\"}");//創(chuàng)建響應(yīng)對象,初始化為成功,沒有指定的話本次請求將不會被攔截actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);}}}?
總結(jié)
以上是生活随笔為你收集整理的web api添加拦截器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 45 张图深度解析 Netty 架构与原
- 下一篇: Dubbo 面试题汇总(附答案)