• 【.NET】WebAPI访问先查看登录状态,重写筛选器ActionFilterAttribute实现


      WebAPI有几个常用的筛选器,都是虚函数类型,只要重写了,就可以在方法、类、派生类使用,属于System.Net.Http.Filter。

      ActionFilterAttribute:Action操作筛选器,一般重写执行前,执行后的2个方法;

      AuthorizationFilterAttribute:授权筛选器,有请求授权时的方法;

      ExceptionFilterAttribute:异常筛选器,有引起异常的方法;

    ActionFilterAttribute重写:

    /// <summary>
        /// 执行操作前的过滤器(可以在方法、类、派生类使用)
        /// </summary>
        [AttributeUsageAttribute(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
        public class MyActionFilter : ActionFilterAttribute 
        {
            /// <summary>
            /// 操作筛选器之前
            /// </summary>
            /// <param name="actionContext"></param>
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                bool Login = true;
                var token = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query).GetValues("token")[0].ToString();
                if (!string.IsNullOrEmpty(token))
                {
                    //获取到token,再判断是否存在
                    if (!ChkToken(token.ToString())) { Login = false; } 
                }
                else
                {
                    Login = false;
                }
    
                if(!Login)
                {
                    //请求返回结果
                    string jsonString = "{"msg":"未登录","code":"-1"}";
                    HttpResponseMessage reqMsg = new HttpResponseMessage { Content=new StringContent(jsonString,System.Text.Encoding.GetEncoding("UTF-8"), "application/json") };
                    actionContext.Response = reqMsg;
                }
                base.OnActionExecuting(actionContext);
            }
        }

      

  • 相关阅读:
    The Preliminary Contest for ICPC China Nanchang National Invitational and International Silk-Road Programming Contest
    HDU 5299 Circles Game
    UVALive
    算法笔记--匈牙利算法
    算法笔记--Splay && Link-Cut-Tree && fhq _treap
    P2685 [TJOI2012]桥
    2017-2018 ACM-ICPC German Collegiate Programming Contest (GCPC 2017)
    ACM-ICPC2018南京赛区 Mediocre String Problem
    Project Euler 345: Matrix Sum
    算法笔记--manacher算法
  • 原文地址:https://www.cnblogs.com/laokchen/p/12355336.html
Copyright © 2020-2023  润新知