[转载]web api添加拦截器

mac2022-06-30  82

实现思路

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); } } }

  

转自:https://www.cnblogs.com/vipstone/p/5827029.html 

 

转载于:https://www.cnblogs.com/wlf921/articles/10083761.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)