开发者社区> 杰克.陈> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客

简介: 原文:WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客 [csharp] view plain copy print? using System;   using System.
+关注继续查看
原文:WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客

  1. using System;  
  2. using System.Linq;  
  3. using System.Web;  
  4. using System.Web.Http;  
  5. using System.Web.Security;  
  6.   
  7. namespace OtherApi.Auth  
  8. {  
  9.   
  10.     public class AuthFilterOutside : AuthorizeAttribute  
  11.     {  
  12.         //重写基类的验证方式,加入我们自定义的Ticket验证  
  13.         public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)  
  14.         {  
  15.             //url获取token  
  16.             var content = actionContext.Request.Properties["MS_HttpContext"as HttpContextBase;  
  17.             var token = content.Request.Headers["Token"];  
  18.             if (!string.IsNullOrEmpty(token))  
  19.             {  
  20.                 //解密用户ticket,并校验用户名密码是否匹配  
  21.                 if (ValidateTicket(token))  
  22.                 {  
  23.                     base.IsAuthorized(actionContext);  
  24.                 }  
  25.                 else  
  26.                 {  
  27.                     HandleUnauthorizedRequest(actionContext);  
  28.                 }  
  29.             }  
  30.             //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401  
  31.             else  
  32.             {  
  33.                 var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();  
  34.                 bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);  
  35.                 if (isAnonymous) base.OnAuthorization(actionContext);  
  36.                 else HandleUnauthorizedRequest(actionContext);  
  37.             }  
  38.         }  
  39.   
  40.         //校验票据(数据库数据匹配)  
  41.         private bool ValidateTicket(string encryptToken)  
  42.         {  
  43.             bool flag = false;  
  44.             try  
  45.             {  
  46.                 //获取数据库Token  
  47.                 Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);  
  48.                 if (model.Token == encryptToken) //存在  
  49.                 {  
  50.                     //未超时  
  51.                     flag = (DateTime.Now <= model.ExpireDate) ? true : false;  
  52.                 }  
  53.             }  
  54.             catch (Exception ex) { }  
  55.             return flag;  
  56.         }  
  57.     }  
  58. }  
using System;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;

namespace OtherApi.Auth
{

    public class AuthFilterOutside : AuthorizeAttribute
    {
        //重写基类的验证方式,加入我们自定义的Ticket验证
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //url获取token
            var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
            var token = content.Request.Headers["Token"];
            if (!string.IsNullOrEmpty(token))
            {
                //解密用户ticket,并校验用户名密码是否匹配
                if (ValidateTicket(token))
                {
                    base.IsAuthorized(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
            //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401
            else
            {
                var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
                bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                if (isAnonymous) base.OnAuthorization(actionContext);
                else HandleUnauthorizedRequest(actionContext);
            }
        }

        //校验票据(数据库数据匹配)
        private bool ValidateTicket(string encryptToken)
        {
            bool flag = false;
            try
            {
                //获取数据库Token
                Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);
                if (model.Token == encryptToken) //存在
                {
                    //未超时
                    flag = (DateTime.Now <= model.ExpireDate) ? true : false;
                }
            }
            catch (Exception ex) { }
            return flag;
        }
    }
}

  1. using System;  
  2. using System.Web;  
  3. using System.Web.Http;  
  4. using System.Web.Security;  
  5. using System.Net.Http;  
  6. using System.Collections.Generic;  
  7. using Newtonsoft.Json;  
  8. using Newtonsoft.Json.Linq;  
  9. using System.Text;  
  10. using OtherApi.Auth;  //引用验证  
  11.   
  12. namespace SpiderApi.Controllers  
  13. {  
  14.     /// <summary>  
  15.     /// 用户授权接口  
  16.     /// </summary>  
  17.     public class AccountController : ApiController  
  18.     {  
  19.         #region 用户登录授权  
  20.         /// <summary>  
  21.         /// 用户登录授权  
  22.         /// </summary>  
  23.         /// <param name="username">用户名</param>  
  24.         /// <param name="password">密码</param>  
  25.         /// <returns></returns>  
  26.         [Route("api/account/login")]  
  27.         [HttpGet]  
  28.         public HttpResponseMessage Login(string username, string password)  
  29.         {  
  30.             //定义  
  31.             ResponseResult obj = new ResponseResult();  
  32.             var model = GetLoginModel(username, password);  
  33.             if (model != null)  
  34.             {  
  35.                 int userId = model.UserId;  
  36.                 string Token = UntilHelper.Md5Encode(UntilHelper.GetExtGuidID(), 32);  
  37.                 var dtNow = DateTime.Now;  
  38.  
  39.                 #region 将身份信息保存票据表中,验证当前请求是否是有效请求  
  40.                 //判断此用户是否存在票据信息  
  41.                 if (Dec.BLL.TicketAuth.GetTicketAuthByUserId(userId) != null)  
  42.                 {  
  43.                     //清空重置  
  44.                     Dec.BLL.TicketAuth.DeleteByUserId(userId);  
  45.                 }  
  46.                 Dec.Models.TicketAuth ticket = new Dec.Models.TicketAuth();  
  47.                 ticket.UserID = userId;  
  48.                 ticket.Token = Token;  
  49.                 ticket.CreateDate = dtNow;  
  50.                 ticket.ExpireDate = dtNow.AddMinutes(30); //30分钟过期  
  51.                 Dec.BLL.TicketAuth.Add(ticket);  
  52.                 #endregion  
  53.   
  54.                 //返回信息              
  55.                 obj.status = true;  
  56.                 obj.message = "用户登录成功";  
  57.                 JObject jo = new JObject();  
  58.                 jo.Add("userid", userId);  
  59.                 jo.Add("loginname", model.LoginName);  
  60.                 jo.Add("nickname", model.NickName);  
  61.                 jo.Add("usertype", model.UserType); //(int)UserTypeEnum.Seller  
  62.                 jo.Add("token", Token);  
  63.                 obj.info = jo;  
  64.             }  
  65.             else  
  66.             {  
  67.                 obj.status = false;  
  68.                 obj.message = "用户登录失败";  
  69.             }  
  70.             var resultObj = JsonConvert.SerializeObject(obj, Formatting.Indented);  
  71.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  72.             return result;  
  73.         }  
  74.         #endregion  
  75.  
  76.         #region 用户退出登录,清空Token  
  77.         /// <summary>  
  78.         /// 用户退出登录,清空Token  
  79.         /// </summary>  
  80.         /// <param name="userId">用户ID</param>  
  81.         /// <returns></returns>  
  82.         [Route("api/account/loginout")]  
  83.         [HttpGet]  
  84.         public HttpResponseMessage LoginOut(int userId)  
  85.         {  
  86.             //定义  
  87.             ResponseResult obj = new ResponseResult();  
  88.             try  
  89.             {  
  90.                 //清空数据库该用户票据数据  
  91.                 Dec.BLL.TicketAuth.DeleteByUserId(userId);  
  92.             }  
  93.             catch (Exception ex) { }  
  94.             //返回信息              
  95.             obj.status = true;  
  96.             obj.message = "成功退出";  
  97.             var resultObj = JsonConvert.SerializeObject(obj);  
  98.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  99.             return result;  
  100.         }  
  101.         #endregion  
  102.  
  103.         #region 查询Token是否有效  
  104.         /// <summary>  
  105.         /// 查询Token是否有效  
  106.         /// </summary>  
  107.         /// <param name="token">token</param>  
  108.         /// <returns></returns>  
  109.         [Route("api/account/validatetoken")]  
  110.         [HttpGet]  
  111.         public HttpResponseMessage ValidateToken(string token)  
  112.         {  
  113.             //定义  
  114.             ResponseResult obj = new ResponseResult();  
  115.             bool flag = ValidateTicket(token);  
  116.             if (flag)  
  117.             {  
  118.                 //返回信息              
  119.                 obj.status = true;  
  120.                 obj.message = "token有效";  
  121.             }  
  122.             else  
  123.             {  
  124.                 obj.status = false;  
  125.                 obj.message = "token无效";  
  126.             }  
  127.             var resultObj = JsonConvert.SerializeObject(obj);  
  128.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  129.             return result;  
  130.         }  
  131.         #endregion  
  132.  
  133.         #region 获取用户账户余额  
  134.         /// <summary>  
  135.         /// 获取用户账户余额  
  136.         /// </summary>  
  137.         /// <param name="userId">用户ID</param>  
  138.         /// <returns></returns>  
  139.         [Route("api/account/amount")]  
  140.         [HttpGet]  
  141.         [AuthFilterOutside] //添加验证  
  142.         public HttpResponseMessage GetAmount(int userId)  
  143.         {  
  144.             //定义  
  145.             ResponseResult obj = new ResponseResult();  
  146.             //获取数据库数据  
  147.             Dec.Models.UserInfo model = Dec.BLL.UserInfo.GetUserInfoByUserId(userId);  
  148.             if (model != null)  
  149.             {  
  150.                 //返回信息              
  151.                 obj.status = true;  
  152.                 obj.message = "获取用户账户余额成功";  
  153.                 JObject jo = new JObject();  
  154.                 jo.Add("userid", model.UserId);  
  155.                 jo.Add("amount", model.Amount);  
  156.                 obj.info = jo;  
  157.             }  
  158.             else  
  159.             {  
  160.                 obj.status = false;  
  161.                 obj.message = "获取用户账户余额失败";  
  162.             }  
  163.   
  164.             var resultObj = JsonConvert.SerializeObject(obj);  
  165.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  166.             return result;  
  167.         }  
  168.         #endregion  
  169.   
  170.         /// <summary>  
  171.         /// 用户充值接口  
  172.         /// </summary>  
  173.         /// <param name="userid">用户ID</param>  
  174.         /// <param name="amount">充值金额</param>  
  175.         /// <returns></returns>  
  176.         [Route("api/account/recharge")]  
  177.         [HttpGet]  
  178.         [AuthFilterInside]  
  179.         public HttpResponseMessage Recharge(string userid, double amount)  
  180.         {  
  181.             //定义  
  182.             ResponseResult obj = new ResponseResult();  
  183.             //获取数据库数据  
  184.   
  185.             //返回信息              
  186.             obj.status = true;  
  187.             obj.message = "操作成功,请等待第三方支付平台返回通知核实是否到账";  
  188.             JObject jo = new JObject();  
  189.             jo.Add("userid""123456789");  
  190.             jo.Add("amount", 125.80);  
  191.             obj.info = jo;  
  192.   
  193.             var resultObj = JsonConvert.SerializeObject(obj);  
  194.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  195.             return result;  
  196.         }  
  197.  
  198.          #region 验证票据是否有效  
  199.         /// <summary>  
  200.         /// 验证票据是否有效  
  201.         /// </summary>  
  202.         /// <param name="encryptToken">token</param>  
  203.         /// <returns></returns>  
  204.         private bool ValidateTicket(string encryptToken)  
  205.         {  
  206.             bool flag = false;  
  207.             try  
  208.             {  
  209.                 //获取数据库Token  
  210.                 Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);  
  211.                 if (model.Token == encryptToken) //存在  
  212.                 {  
  213.                     //未超时  
  214.                     flag = (DateTime.Now <= model.ExpireDate) ? true : false;  
  215.                 }  
  216.             }  
  217.             catch (Exception ex) { }  
  218.             return flag;  
  219.         }  
  220.         #endregion  
  221.  
  222.         #region 用户登录  
  223.         /// <summary>  
  224.         /// 用户登录  
  225.         /// </summary>  
  226.         /// <param name="userName">用户名</param>  
  227.         /// <param name="userPwd">密码</param>  
  228.         /// <returns></returns>  
  229.         private Dec.Models.UserInfo GetLoginModel(string userName, string userPwd)  
  230.         {  
  231.             Dec.Models.UserInfo model = new Dec.Models.UserInfo();  
  232.             try  
  233.             {  
  234.                 if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(userPwd))  
  235.                 {  
  236.                     //数据库比对  
  237.                     model = Dec.BLL.UserInfo.GetUserInfoByUserNamePwd(userName, UntilHelper.Md5Encode(userPwd, 32));  
  238.                 }  
  239.             }  
  240.             catch (Exception ex) { }  
  241.             return model;  
  242.         }  
  243.         #endregion  
  244.     }  
  245. }  
using System;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Net.Http;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using OtherApi.Auth;  //引用验证

namespace SpiderApi.Controllers
{
    /// <summary>
    /// 用户授权接口
    /// </summary>
    public class AccountController : ApiController
    {
        #region 用户登录授权
        /// <summary>
        /// 用户登录授权
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [Route("api/account/login")]
        [HttpGet]
        public HttpResponseMessage Login(string username, string password)
        {
            //定义
            ResponseResult obj = new ResponseResult();
            var model = GetLoginModel(username, password);
            if (model != null)
            {
                int userId = model.UserId;
                string Token = UntilHelper.Md5Encode(UntilHelper.GetExtGuidID(), 32);
                var dtNow = DateTime.Now;

                #region 将身份信息保存票据表中,验证当前请求是否是有效请求
                //判断此用户是否存在票据信息
                if (Dec.BLL.TicketAuth.GetTicketAuthByUserId(userId) != null)
                {
                    //清空重置
                    Dec.BLL.TicketAuth.DeleteByUserId(userId);
                }
                Dec.Models.TicketAuth ticket = new Dec.Models.TicketAuth();
                ticket.UserID = userId;
                ticket.Token = Token;
                ticket.CreateDate = dtNow;
                ticket.ExpireDate = dtNow.AddMinutes(30); //30分钟过期
                Dec.BLL.TicketAuth.Add(ticket);
                #endregion

                //返回信息            
                obj.status = true;
                obj.message = "用户登录成功";
                JObject jo = new JObject();
                jo.Add("userid", userId);
                jo.Add("loginname", model.LoginName);
                jo.Add("nickname", model.NickName);
                jo.Add("usertype", model.UserType); //(int)UserTypeEnum.Seller
                jo.Add("token", Token);
                obj.info = jo;
            }
            else
            {
                obj.status = false;
                obj.message = "用户登录失败";
            }
            var resultObj = JsonConvert.SerializeObject(obj, Formatting.Indented);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion

        #region 用户退出登录,清空Token
        /// <summary>
        /// 用户退出登录,清空Token
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [Route("api/account/loginout")]
        [HttpGet]
        public HttpResponseMessage LoginOut(int userId)
        {
            //定义
            ResponseResult obj = new ResponseResult();
            try
            {
                //清空数据库该用户票据数据
                Dec.BLL.TicketAuth.DeleteByUserId(userId);
            }
            catch (Exception ex) { }
            //返回信息            
            obj.status = true;
            obj.message = "成功退出";
            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion

        #region 查询Token是否有效
        /// <summary>
        /// 查询Token是否有效
        /// </summary>
        /// <param name="token">token</param>
        /// <returns></returns>
        [Route("api/account/validatetoken")]
        [HttpGet]
        public HttpResponseMessage ValidateToken(string token)
        {
            //定义
            ResponseResult obj = new ResponseResult();
            bool flag = ValidateTicket(token);
            if (flag)
            {
                //返回信息            
                obj.status = true;
                obj.message = "token有效";
            }
            else
            {
                obj.status = false;
                obj.message = "token无效";
            }
            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion

        #region 获取用户账户余额
        /// <summary>
        /// 获取用户账户余额
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [Route("api/account/amount")]
        [HttpGet]
        [AuthFilterOutside] //添加验证
        public HttpResponseMessage GetAmount(int userId)
        {
            //定义
            ResponseResult obj = new ResponseResult();
            //获取数据库数据
            Dec.Models.UserInfo model = Dec.BLL.UserInfo.GetUserInfoByUserId(userId);
            if (model != null)
            {
                //返回信息            
                obj.status = true;
                obj.message = "获取用户账户余额成功";
                JObject jo = new JObject();
                jo.Add("userid", model.UserId);
                jo.Add("amount", model.Amount);
                obj.info = jo;
            }
            else
            {
                obj.status = false;
                obj.message = "获取用户账户余额失败";
            }

            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion

        /// <summary>
        /// 用户充值接口
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <param name="amount">充值金额</param>
        /// <returns></returns>
        [Route("api/account/recharge")]
        [HttpGet]
        [AuthFilterInside]
        public HttpResponseMessage Recharge(string userid, double amount)
        {
            //定义
            ResponseResult obj = new ResponseResult();
            //获取数据库数据

            //返回信息            
            obj.status = true;
            obj.message = "操作成功,请等待第三方支付平台返回通知核实是否到账";
            JObject jo = new JObject();
            jo.Add("userid", "123456789");
            jo.Add("amount", 125.80);
            obj.info = jo;

            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

         #region 验证票据是否有效
        /// <summary>
        /// 验证票据是否有效
        /// </summary>
        /// <param name="encryptToken">token</param>
        /// <returns></returns>
        private bool ValidateTicket(string encryptToken)
        {
            bool flag = false;
            try
            {
                //获取数据库Token
                Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);
                if (model.Token == encryptToken) //存在
                {
                    //未超时
                    flag = (DateTime.Now <= model.ExpireDate) ? true : false;
                }
            }
            catch (Exception ex) { }
            return flag;
        }
        #endregion

        #region 用户登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userPwd">密码</param>
        /// <returns></returns>
        private Dec.Models.UserInfo GetLoginModel(string userName, string userPwd)
        {
            Dec.Models.UserInfo model = new Dec.Models.UserInfo();
            try
            {
                if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(userPwd))
                {
                    //数据库比对
                    model = Dec.BLL.UserInfo.GetUserInfoByUserNamePwd(userName, UntilHelper.Md5Encode(userPwd, 32));
                }
            }
            catch (Exception ex) { }
            return model;
        }
        #endregion
    }
}
  1. //////////////////////////////////////////////////////////////////  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Http;  
  7. using System.Web.Mvc;  
  8. using System.Web.Routing;  
  9.   
  10. namespace SpiderApi  
  11. {  
  12.     public class WebApiApplication : System.Web.HttpApplication  
  13.     {  
  14.         protected void Application_Start()  
  15.         {  
  16.             //WebApi文档  
  17.             AreaRegistration.RegisterAllAreas();  
  18.             GlobalConfiguration.Configure(WebApiConfig.Register);  
  19.         }  
  20.   
  21.         protected void Application_PostAuthorizeRequest()  
  22.         {  
  23.             //Enable Session  
  24.             HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);  
  25.         }  
  26.     }  
  27. }  
//////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

namespace SpiderApi
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //WebApi文档
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

        protected void Application_PostAuthorizeRequest()
        {
            //Enable Session
            HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
        }
    }
}
  1. // Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData  
  2. // package to your project. 先安装Help Page包  HelpPage=>App_start=>HelpPageConfig.cs  
  3. ////#define Handle_PageResultOfT  
  4.   
  5. using System;  
  6. using System.Collections;  
  7. using System.Collections.Generic;  
  8. using System.Diagnostics;  
  9. using System.Diagnostics.CodeAnalysis;  
  10. using System.Linq;  
  11. using System.Net.Http.Headers;  
  12. using System.Reflection;  
  13. using System.Web;  
  14. using System.Web.Http;  
  15. using SpiderApi.Models;  
  16. #if Handle_PageResultOfT  
  17. using System.Web.Http.OData;  
  18. #endif  
  19.   
  20. namespace SpiderApi.Areas.HelpPage  
  21. {  
  22.     /// <summary>  
  23.     /// Use this class to customize the Help Page.  
  24.     /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation  
  25.     /// or you can provide the samples for the requests/responses.  
  26.     /// </summary>  
  27.     public static class HelpPageConfig  
  28.     {  
  29.         [SuppressMessage("Microsoft.Globalization""CA1303:Do not pass literals as localized parameters",  
  30.             MessageId = "SpiderApi.Areas.HelpPage.TextSample.#ctor(System.String)",  
  31.             Justification = "End users may choose to merge this string with existing localized resources.")]  
  32.         [SuppressMessage("Microsoft.Naming""CA2204:Literals should be spelled correctly",  
  33.             MessageId = "bsonspec",  
  34.             Justification = "Part of a URI.")]  
  35.         public static void Register(HttpConfiguration config)  
  36.         {  
  37.             //// Uncomment the following to use the documentation from XML documentation file.  
  38.             //开启解析  
  39.             config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/Bin/SpiderApi.XML")));  
  40.   
  41.             //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.  
  42.             //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type   
  43.             //// formats by the available formatters.  
  44.             //config.SetSampleObjects(new Dictionary<Type, object>  
  45.             //{  
  46.             //    {typeof(string), "sample string"},  
  47.             //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}  
  48.             //});  
  49.             //添加映射  
  50.             config.SetSampleResponse(Sample.BatchSendMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""BatchSendMessage");  
  51.             config.SetSampleResponse(Sample.BatchReceiveMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""BatchReceiveMessage");  
  52.             config.SetSampleResponse(Sample.DeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""DeleteMessage");  
  53.             config.SetSampleResponse(Sample.BatchDeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""BatchDeleteMessage");  
  54.             config.SetSampleResponse(Sample.ChangeMessageVisibilityResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""ChangeMessageVisibility");  
  55.   
  56.             // Extend the following to provide factories for types not handled automatically (those lacking parameterless  
  57.             // constructors) or for which you prefer to use non-default property values. Line below provides a fallback  
  58.             // since automatic handling will fail and GeneratePageResult handles only a single type.  
  59. #if Handle_PageResultOfT  
  60.             config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);  
  61. #endif  
  62.   
  63.             // Extend the following to use a preset object directly as the sample for all actions that support a media  
  64.             // type, regardless of the body parameter or return type. The lines below avoid display of binary content.  
  65.             // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.  
  66.             config.SetSampleForMediaType(  
  67.                 new TextSample("Binary JSON content. See http://bsonspec.org for details."),  
  68.                 new MediaTypeHeaderValue("application/bson"));  
  69.   
  70.             //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format  
  71.             //// and have IEnumerable<string> as the body parameter or return type.  
  72.             //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));  
  73.   
  74.             //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"  
  75.             //// and action named "Put".  
  76.             //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");  
  77.   
  78.             //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"  
  79.             //// on the controller named "Values" and action named "Get" with parameter "id".  
  80.             //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");  
  81.   
  82.             //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.  
  83.             //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.  
  84.             //config.SetActualRequestType(typeof(string), "Values", "Get");  
  85.   
  86.             //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.  
  87.             //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.  
  88.             //config.SetActualResponseType(typeof(string), "Values", "Post");  
  89.         }  
  90.  
  91. #if Handle_PageResultOfT  
  92.         private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)  
  93.         {  
  94.             if (type.IsGenericType)  
  95.             {  
  96.                 Type openGenericType = type.GetGenericTypeDefinition();  
  97.                 if (openGenericType == typeof(PageResult<>))  
  98.                 {  
  99.                     // Get the T in PageResult<T>  
  100.                     Type[] typeParameters = type.GetGenericArguments();  
  101.                     Debug.Assert(typeParameters.Length == 1);  
  102.   
  103.                     // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor  
  104.                     Type itemsType = typeof(List<>).MakeGenericType(typeParameters);  
  105.                     object items = sampleGenerator.GetSampleObject(itemsType);  
  106.   
  107.                     // Fill in the other information needed to invoke the PageResult<T> constuctor  
  108.                     Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };  
  109.                     object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };  
  110.   
  111.                     // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor  
  112.                     ConstructorInfo constructor = type.GetConstructor(parameterTypes);  
  113.                     return constructor.Invoke(parameters);  
  114.                 }  
  115.             }  
  116.   
  117.             return null;  
  118.         }  
  119. #endif  
  120.     }  
  121. }  
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project. 先安装Help Page包  HelpPage=>App_start=>HelpPageConfig.cs
////#define Handle_PageResultOfT

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
using SpiderApi.Models;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif

namespace SpiderApi.Areas.HelpPage
{
    /// <summary>
    /// Use this class to customize the Help Page.
    /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
    /// or you can provide the samples for the requests/responses.
    /// </summary>
    public static class HelpPageConfig
    {
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
            MessageId = "SpiderApi.Areas.HelpPage.TextSample.#ctor(System.String)",
            Justification = "End users may choose to merge this string with existing localized resources.")]
        [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
            MessageId = "bsonspec",
            Justification = "Part of a URI.")]
        public static void Register(HttpConfiguration config)
        {
            //// Uncomment the following to use the documentation from XML documentation file.
            //开启解析
            config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/Bin/SpiderApi.XML")));

            //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
            //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type 
            //// formats by the available formatters.
            //config.SetSampleObjects(new Dictionary<Type, object>
            //{
            //    {typeof(string), "sample string"},
            //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
            //});
            //添加映射
            config.SetSampleResponse(Sample.BatchSendMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchSendMessage");
            config.SetSampleResponse(Sample.BatchReceiveMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchReceiveMessage");
            config.SetSampleResponse(Sample.DeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "DeleteMessage");
            config.SetSampleResponse(Sample.BatchDeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchDeleteMessage");
            config.SetSampleResponse(Sample.ChangeMessageVisibilityResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "ChangeMessageVisibility");

            // Extend the following to provide factories for types not handled automatically (those lacking parameterless
            // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
            // since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif

            // Extend the following to use a preset object directly as the sample for all actions that support a media
            // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
            // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
            config.SetSampleForMediaType(
                new TextSample("Binary JSON content. See http://bsonspec.org for details."),
                new MediaTypeHeaderValue("application/bson"));

            //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
            //// and have IEnumerable<string> as the body parameter or return type.
            //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));

            //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
            //// and action named "Put".
            //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");

            //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
            //// on the controller named "Values" and action named "Get" with parameter "id".
            //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");

            //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
            //config.SetActualRequestType(typeof(string), "Values", "Get");

            //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
            //config.SetActualResponseType(typeof(string), "Values", "Post");
        }

#if Handle_PageResultOfT
        private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
        {
            if (type.IsGenericType)
            {
                Type openGenericType = type.GetGenericTypeDefinition();
                if (openGenericType == typeof(PageResult<>))
                {
                    // Get the T in PageResult<T>
                    Type[] typeParameters = type.GetGenericArguments();
                    Debug.Assert(typeParameters.Length == 1);

                    // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
                    Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
                    object items = sampleGenerator.GetSampleObject(itemsType);

                    // Fill in the other information needed to invoke the PageResult<T> constuctor
                    Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
                    object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };

                    // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
                    ConstructorInfo constructor = type.GetConstructor(parameterTypes);
                    return constructor.Invoke(parameters);
                }
            }

            return null;
        }
#endif
    }
}
  1. /* 
  2. API接口测试工具 - WebApiTestClient使用--Nuget引入组件  
  3. --A Simple Test Client for ASP.NET Web API 
  4. */  
  5. /* 
  6. 1、修改Api.cshtml文件 
  7. 通过上述步骤,就能将组件WebAPITestClient引入进来。下面我们只需要做一件事:打开文件 (根据 Areas\HelpPage\Views\Help) Api.cshtml 并添加以下内容: 
  8.  
  9. @Html.DisplayForModel("TestClientDialogs") 
  10. @Html.DisplayForModel("TestClientReferences") 
  11. 添加后Api.cshtml文件的代码如下 
  12. */  
  13.   
  14.   
  15. @using System.Web.Http  
  16. @using WebApiTestClient.Areas.HelpPage.Models  
  17. @model HelpPageApiModel  
  18.   
  19. @{  
  20.     var description = Model.ApiDescription;  
  21.     ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath;  
  22. }  
  23.   
  24. <link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />  
  25. <div id="body" class="help-page">  
  26.     <section class="featured">  
  27.         <div class="content-wrapper">  
  28.             <p>  
  29.                 @Html.ActionLink("Help Page Home""Index")  
  30.             </p>  
  31.         </div>  
  32.     </section>  
  33.     <section class="content-wrapper main-content clear-fix">  
  34.         @Html.DisplayForModel()  
  35.     </section>  
  36. </div>  
  37.   
  38. @Html.DisplayForModel("TestClientDialogs")  
  39. @section Scripts{  
  40.     <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />  
  41.     @Html.DisplayForModel("TestClientReferences")  
  42. }  
/*
API接口测试工具 - WebApiTestClient使用--Nuget引入组件 
--A Simple Test Client for ASP.NET Web API
*/
/*
1、修改Api.cshtml文件
通过上述步骤,就能将组件WebAPITestClient引入进来。下面我们只需要做一件事:打开文件 (根据 Areas\HelpPage\Views\Help) Api.cshtml 并添加以下内容:

@Html.DisplayForModel("TestClientDialogs")
@Html.DisplayForModel("TestClientReferences")
添加后Api.cshtml文件的代码如下
*/


@using System.Web.Http
@using WebApiTestClient.Areas.HelpPage.Models
@model HelpPageApiModel

@{
    var description = Model.ApiDescription;
    ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath;
}

<link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
<div id="body" class="help-page">
    <section class="featured">
        <div class="content-wrapper">
            <p>
                @Html.ActionLink("Help Page Home", "Index")
            </p>
        </div>
    </section>
    <section class="content-wrapper main-content clear-fix">
        @Html.DisplayForModel()
    </section>
</div>

@Html.DisplayForModel("TestClientDialogs")
@section Scripts{
    <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
    @Html.DisplayForModel("TestClientReferences")
}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
若依实现单点登录(解析请求链接中的参数做鉴权认证)
若依实现单点登录(解析请求链接中的参数做鉴权认证)
0 0
ASP.NET Core : 二十七. JWT与用户授权(细化到Action)(二)
上一章分享了如何在ASP.NET Core中应用JWT进行用户认证以及Token的刷新,本章继续进行下一步,用户授权。涉及到的例子也以上一章的为基础。
0 0
ASP.NET Core : 二十七. JWT与用户授权(细化到Action)(一)
上一章分享了如何在ASP.NET Core中应用JWT进行用户认证以及Token的刷新,本章继续进行下一步,用户授权。涉及到的例子也以上一章的为基础。
0 0
ASP.NET WebApi 基于JWT实现Token签名认证(发布版)
一、前言 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性。那么对于我们来说,如何确保数据的安全将会是需要思考的问题。在ASP.NET WebService服务中可以通过SoapHead验证机制来实现,那么在ASP.NET WebApi中我们应该如何保证我们的接口安全呢?在上此分享课程中阿笨给大家带来了传统的基于Session方式的Token签名验证,那么本次分享课程阿笨给大家带来另外一种基于JWT方式解决方案。
3972 0
ASP.NET WebApi 基于分布式Session方式实现Token签名认证(发布版)
一、课程介绍 明人不说暗话,跟着阿笨一起学玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性。那么对于我们来说,如何确保数据的安全将会是需要思考的问题。在ASP.NETWebService服务中可以通过SoapHead验证机制来实现,那么在ASP.NET WebApi中我们应该如何保证我们的接口安全呢?如果您对本次分享课程《ASP.NET WebApi 基于分布式Session方式实现Token签名认证》感兴趣的话,那么请跟踪阿笨一起学习吧。
2165 0
怎样使用Fiddler获取WebApi的token值?
User-Agent: Fiddler Host: localhost:16805 Content-Length: 51 Content-Type: application/json grant_type=password&username=wsw&password=198006...
997 0
+关注
杰克.陈
一个安静的程序猿~
文章
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载