asp.net webapi+swagger+OAuth2.0

文档继续完善整理中。。。。。。

c.DocumentFilter<SwaggerDocTag>();

 /// <summary>
    /// Swagger注释帮助类
    /// </summary>
    public class SwaggerDocTag : IDocumentFilter
    {
        /// <summary>
        /// 添加附加注释
        /// </summary>
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            //swaggerDoc.tags = new List<Tag>
            //{
            //    //添加对应的控制器描述 这个是我好不容易在issues里面翻到的
            //    new Tag { name = "Home", description = "后台" },
            //    new Tag { name = "Client", description = "客户端" },
            //    new Tag { name = "System", description = "系统" }
            //};
            swaggerDoc.tags = GetControllerDesc();
        }

        /// <summary>
        /// 从xml注释中读取控制器注释
        /// </summary>
        /// <returns></returns>
        private List<Tag> GetControllerDesc()
        {
            List<Tag> tagList = new List<Tag>();

            var xmlpath = string.Format(string.Format("{0}/bin/Eternal.WebAPI.xml", System.AppDomain.CurrentDomain.BaseDirectory));
            if (!File.Exists(xmlpath))//检查xml注释文件是否存在
                return tagList;

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlpath);

            string memberName = string.Empty;//xml三级节点的name属性值
            string controllerName = string.Empty;//控制器完整名称
            string key = string.Empty;//控制器去Controller名称
            string value = string.Empty;//控制器注释

            foreach (XmlNode node in xmlDoc.SelectNodes("//member"))//循环三级节点member
            {
                memberName = node.Attributes["name"].Value;
                if (memberName.StartsWith("T:"))//T:开头的代表类
                {
                    string[] arrPath = memberName.Split('.');
                    controllerName = arrPath[arrPath.Length - 1];
                    if (controllerName.EndsWith("Controller"))//Controller结尾的代表控制器
                    {
                        XmlNode summaryNode = node.SelectSingleNode("summary");//注释节点
                        key = controllerName.Remove(controllerName.Length - "Controller".Length, "Controller".Length);
                        if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !tagList.Contains(new Tag { name = key }))
                        {
                            value = summaryNode.InnerText.Trim();
                            tagList.Add(new Tag { name = key, description = value });
                        }
                    }
                }
            }
            return tagList;
        }
swagger显示控制器注释
  /**
    * Get Code
    */
    AuthHttpClient.prototype.getCode = function (url, client_id, callback, errorCallback, statusCodeCallback) {
        //&scope=admin
        $.ajax(url + 'authorize?response_type=code&scope=xxx&client_id=' + client_id + "&redirect_uri=" + window.location.href, {
            type: 'POST',
            async:false,
            success: function (data, textStatus, jqXHR) {
                if (callback !== null) {
                    callback(data);
                    sessionStorage.setItem("registered_redirect_uri", location.href);
                    location.href = data;
                    return false;
                }
            },
            error: function (xhr, ajaxOptions, thrown) {
                if (errorCallback !== null) {
                    errorCallback(xhr, ajaxOptions, thrown);
                }
            },
            statusCode: statusCodeCallback
        });
    };
    /**
    * Get Implicit
    */
    AuthHttpClient.prototype.getImplicitToken = function (url, client_id, callback, errorCallback, statusCodeCallback) {
        if (location.hash.indexOf('access_token') !== -1) {
            var urlpar = location.hash.substr(1).split("&");
            for (var key in urlpar) {
                var parm = urlpar[key].split("=");
                sessionStorage.setItem(parm[0], parm[1]);
            }
        }
        else {
            location.href = url + 'authorize?response_type=token&client_id=' + client_id + "&redirect_uri=" + window.location.href;
        }
    };
    /**
    * Get 密码
    */
    AuthHttpClient.prototype.getPassWordToken = function (url, username, password, client_id, client_secret) {
        $.ajax(url + 'token', {
            data: {
                'grant_type': 'password',
                'username': username,
                'password': password,
                'client_id': client_id,
                'client_secret': client_secret
            },
            async: false,
            type: 'post',
            success: function (data, textStatus, jqXHR) {
                if (data !== null && data !== '') {
                    sessionStorage.setItem("access_token", data.access_token);
                    sessionStorage.setItem("expires_in", data.expires_in);
                }
            },
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            headers: {
                Accept: 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8'
            }
        });
    };

    /**
 * 客户端
 */
    AuthHttpClient.prototype.getClientToken = function (url, client_id, client_secret, callback, errorCallback, statusCodeCallback) {
        $.ajax(url + 'token', {
            data: {
                'grant_type': 'client_credentials',
                'client_id': client_id,
                'client_secret': client_secret
            },
            type: 'POST',
            success: function (data, textStatus, jqXHR) {
                if (data !== null && data !== '') {
                    sessionStorage.setItem("access_token", data.access_token);
                    sessionStorage.setItem("expires_in", data.expires_in);
                }
                if (callback !== null) {
                    callback(data);
                }
            },
            error: function (xhr, ajaxOptions, thrown) {
                if (errorCallback !== null) {
                    errorCallback(xhr, ajaxOptions, thrown);
                }
            },
            statusCode: statusCodeCallback,
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            headers: {
                Accept: 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8'
            }
        });
    };

    /**
    * Get Token
    */
    AuthHttpClient.prototype.getToken = function (url,grant_type,client_id, client_secret, callback, errorCallback, statusCodeCallback) {
        $.ajax(url + 'token', {
            data: {
                'grant_type': 'authorization_code',
                'client_id': client_id,
                'client_secret': client_secret,
                'code': new AuthHttpClient().request('code'),
                'redirect_uri': sessionStorage.getItem('registered_redirect_uri')
            },
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Basic ' +new AuthHttpClient().base64_Encode(client_id + ':' + client_secret));
            },
            async: false,
            type: 'post',
            success: function (data, textStatus, jqXHR) {
                if (data !== null && data !== '') {
                    sessionStorage.setItem("access_token", data.access_token);
                    sessionStorage.setItem("expires_in", data.expires_in);
                }
                if (callback !== null) {
                    callback(data);
                }
            },
            error: function (xhr, ajaxOptions, thrown) {
                if (errorCallback !== null) {
                    
                    errorCallback(xhr, ajaxOptions, thrown);
                }
            },
            statusCode: statusCodeCallback,
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            headers: {
                Accept: 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8'
            }
        });
    };

  

猜你喜欢

转载自www.cnblogs.com/xxxin/p/9675724.html