zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    
    }
    
  • 相关阅读:
    48. Rotate Image
    47. Permutations II
    46. Permutations
    45. Jump Game II
    44. Wildcard Matching
    43. Multiply Strings
    42. Trapping Rain Water
    Python_匿名函数
    Python_内置函数之map()
    Python_面向对象_单例模式
  • 原文地址:https://www.cnblogs.com/vipstone/p/5827029.html
Copyright © 2011-2022 走看看