实现思路
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);
}
}
}