原文: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. namespace OtherApi.Auth
  7. {
  8. public class AuthFilterOutside : AuthorizeAttribute
  9. {
  10. //重写基类的验证方式,加入我们自定义的Ticket验证
  11. public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
  12. {
  13. //url获取token
  14. var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
  15. var token = content.Request.Headers["Token"];
  16. if (!string.IsNullOrEmpty(token))
  17. {
  18. //解密用户ticket,并校验用户名密码是否匹配
  19. if (ValidateTicket(token))
  20. {
  21. base.IsAuthorized(actionContext);
  22. }
  23. else
  24. {
  25. HandleUnauthorizedRequest(actionContext);
  26. }
  27. }
  28. //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401
  29. else
  30. {
  31. var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
  32. bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
  33. if (isAnonymous) base.OnAuthorization(actionContext);
  34. else HandleUnauthorizedRequest(actionContext);
  35. }
  36. }
  37. //校验票据(数据库数据匹配)
  38. private bool ValidateTicket(string encryptToken)
  39. {
  40. bool flag = false;
  41. try
  42. {
  43. //获取数据库Token
  44. Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);
  45. if (model.Token == encryptToken) //存在
  46. {
  47. //未超时
  48. flag = (DateTime.Now <= model.ExpireDate) ? true : false;
  49. }
  50. }
  51. catch (Exception ex) { }
  52. return flag;
  53. }
  54. }
  55. }
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. namespace SpiderApi.Controllers
  12. {
  13. /// <summary>
  14. /// 用户授权接口
  15. /// </summary>
  16. public class AccountController : ApiController
  17. {
  18. #region 用户登录授权
  19. /// <summary>
  20. /// 用户登录授权
  21. /// </summary>
  22. /// <param name="username">用户名</param>
  23. /// <param name="password">密码</param>
  24. /// <returns></returns>
  25. [Route("api/account/login")]
  26. [HttpGet]
  27. public HttpResponseMessage Login(string username, string password)
  28. {
  29. //定义
  30. ResponseResult obj = new ResponseResult();
  31. var model = GetLoginModel(username, password);
  32. if (model != null)
  33. {
  34. int userId = model.UserId;
  35. string Token = UntilHelper.Md5Encode(UntilHelper.GetExtGuidID(), 32);
  36. var dtNow = DateTime.Now;
  37. #region 将身份信息保存票据表中,验证当前请求是否是有效请求
  38. //判断此用户是否存在票据信息
  39. if (Dec.BLL.TicketAuth.GetTicketAuthByUserId(userId) != null)
  40. {
  41. //清空重置
  42. Dec.BLL.TicketAuth.DeleteByUserId(userId);
  43. }
  44. Dec.Models.TicketAuth ticket = new Dec.Models.TicketAuth();
  45. ticket.UserID = userId;
  46. ticket.Token = Token;
  47. ticket.CreateDate = dtNow;
  48. ticket.ExpireDate = dtNow.AddMinutes(30); //30分钟过期
  49. Dec.BLL.TicketAuth.Add(ticket);
  50. #endregion
  51. //返回信息
  52. obj.status = true;
  53. obj.message = "用户登录成功";
  54. JObject jo = new JObject();
  55. jo.Add("userid", userId);
  56. jo.Add("loginname", model.LoginName);
  57. jo.Add("nickname", model.NickName);
  58. jo.Add("usertype", model.UserType); //(int)UserTypeEnum.Seller
  59. jo.Add("token", Token);
  60. obj.info = jo;
  61. }
  62. else
  63. {
  64. obj.status = false;
  65. obj.message = "用户登录失败";
  66. }
  67. var resultObj = JsonConvert.SerializeObject(obj, Formatting.Indented);
  68. HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
  69. return result;
  70. }
  71. #endregion
  72. #region 用户退出登录,清空Token
  73. /// <summary>
  74. /// 用户退出登录,清空Token
  75. /// </summary>
  76. /// <param name="userId">用户ID</param>
  77. /// <returns></returns>
  78. [Route("api/account/loginout")]
  79. [HttpGet]
  80. public HttpResponseMessage LoginOut(int userId)
  81. {
  82. //定义
  83. ResponseResult obj = new ResponseResult();
  84. try
  85. {
  86. //清空数据库该用户票据数据
  87. Dec.BLL.TicketAuth.DeleteByUserId(userId);
  88. }
  89. catch (Exception ex) { }
  90. //返回信息
  91. obj.status = true;
  92. obj.message = "成功退出";
  93. var resultObj = JsonConvert.SerializeObject(obj);
  94. HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
  95. return result;
  96. }
  97. #endregion
  98. #region 查询Token是否有效
  99. /// <summary>
  100. /// 查询Token是否有效
  101. /// </summary>
  102. /// <param name="token">token</param>
  103. /// <returns></returns>
  104. [Route("api/account/validatetoken")]
  105. [HttpGet]
  106. public HttpResponseMessage ValidateToken(string token)
  107. {
  108. //定义
  109. ResponseResult obj = new ResponseResult();
  110. bool flag = ValidateTicket(token);
  111. if (flag)
  112. {
  113. //返回信息
  114. obj.status = true;
  115. obj.message = "token有效";
  116. }
  117. else
  118. {
  119. obj.status = false;
  120. obj.message = "token无效";
  121. }
  122. var resultObj = JsonConvert.SerializeObject(obj);
  123. HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
  124. return result;
  125. }
  126. #endregion
  127. #region 获取用户账户余额
  128. /// <summary>
  129. /// 获取用户账户余额
  130. /// </summary>
  131. /// <param name="userId">用户ID</param>
  132. /// <returns></returns>
  133. [Route("api/account/amount")]
  134. [HttpGet]
  135. [AuthFilterOutside] //添加验证
  136. public HttpResponseMessage GetAmount(int userId)
  137. {
  138. //定义
  139. ResponseResult obj = new ResponseResult();
  140. //获取数据库数据
  141. Dec.Models.UserInfo model = Dec.BLL.UserInfo.GetUserInfoByUserId(userId);
  142. if (model != null)
  143. {
  144. //返回信息
  145. obj.status = true;
  146. obj.message = "获取用户账户余额成功";
  147. JObject jo = new JObject();
  148. jo.Add("userid", model.UserId);
  149. jo.Add("amount", model.Amount);
  150. obj.info = jo;
  151. }
  152. else
  153. {
  154. obj.status = false;
  155. obj.message = "获取用户账户余额失败";
  156. }
  157. var resultObj = JsonConvert.SerializeObject(obj);
  158. HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
  159. return result;
  160. }
  161. #endregion
  162. /// <summary>
  163. /// 用户充值接口
  164. /// </summary>
  165. /// <param name="userid">用户ID</param>
  166. /// <param name="amount">充值金额</param>
  167. /// <returns></returns>
  168. [Route("api/account/recharge")]
  169. [HttpGet]
  170. [AuthFilterInside]
  171. public HttpResponseMessage Recharge(string userid, double amount)
  172. {
  173. //定义
  174. ResponseResult obj = new ResponseResult();
  175. //获取数据库数据
  176. //返回信息
  177. obj.status = true;
  178. obj.message = "操作成功,请等待第三方支付平台返回通知核实是否到账";
  179. JObject jo = new JObject();
  180. jo.Add("userid", "123456789");
  181. jo.Add("amount", 125.80);
  182. obj.info = jo;
  183. var resultObj = JsonConvert.SerializeObject(obj);
  184. HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
  185. return result;
  186. }
  187. #region 验证票据是否有效
  188. /// <summary>
  189. /// 验证票据是否有效
  190. /// </summary>
  191. /// <param name="encryptToken">token</param>
  192. /// <returns></returns>
  193. private bool ValidateTicket(string encryptToken)
  194. {
  195. bool flag = false;
  196. try
  197. {
  198. //获取数据库Token
  199. Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);
  200. if (model.Token == encryptToken) //存在
  201. {
  202. //未超时
  203. flag = (DateTime.Now <= model.ExpireDate) ? true : false;
  204. }
  205. }
  206. catch (Exception ex) { }
  207. return flag;
  208. }
  209. #endregion
  210. #region 用户登录
  211. /// <summary>
  212. /// 用户登录
  213. /// </summary>
  214. /// <param name="userName">用户名</param>
  215. /// <param name="userPwd">密码</param>
  216. /// <returns></returns>
  217. private Dec.Models.UserInfo GetLoginModel(string userName, string userPwd)
  218. {
  219. Dec.Models.UserInfo model = new Dec.Models.UserInfo();
  220. try
  221. {
  222. if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(userPwd))
  223. {
  224. //数据库比对
  225. model = Dec.BLL.UserInfo.GetUserInfoByUserNamePwd(userName, UntilHelper.Md5Encode(userPwd, 32));
  226. }
  227. }
  228. catch (Exception ex) { }
  229. return model;
  230. }
  231. #endregion
  232. }
  233. }
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. namespace SpiderApi
  10. {
  11. public class WebApiApplication : System.Web.HttpApplication
  12. {
  13. protected void Application_Start()
  14. {
  15. //WebApi文档
  16. AreaRegistration.RegisterAllAreas();
  17. GlobalConfiguration.Configure(WebApiConfig.Register);
  18. }
  19. protected void Application_PostAuthorizeRequest()
  20. {
  21. //Enable Session
  22. HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
  23. }
  24. }
  25. }
//////////////////////////////////////////////////////////////////
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. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Diagnostics.CodeAnalysis;
  9. using System.Linq;
  10. using System.Net.Http.Headers;
  11. using System.Reflection;
  12. using System.Web;
  13. using System.Web.Http;
  14. using SpiderApi.Models;
  15. #if Handle_PageResultOfT
  16. using System.Web.Http.OData;
  17. #endif
  18. namespace SpiderApi.Areas.HelpPage
  19. {
  20. /// <summary>
  21. /// Use this class to customize the Help Page.
  22. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
  23. /// or you can provide the samples for the requests/responses.
  24. /// </summary>
  25. public static class HelpPageConfig
  26. {
  27. [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
  28. MessageId = "SpiderApi.Areas.HelpPage.TextSample.#ctor(System.String)",
  29. Justification = "End users may choose to merge this string with existing localized resources.")]
  30. [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
  31. MessageId = "bsonspec",
  32. Justification = "Part of a URI.")]
  33. public static void Register(HttpConfiguration config)
  34. {
  35. //// Uncomment the following to use the documentation from XML documentation file.
  36. //开启解析
  37. config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/Bin/SpiderApi.XML")));
  38. //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
  39. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
  40. //// formats by the available formatters.
  41. //config.SetSampleObjects(new Dictionary<Type, object>
  42. //{
  43. //    {typeof(string), "sample string"},
  44. //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
  45. //});
  46. //添加映射
  47. config.SetSampleResponse(Sample.BatchSendMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchSendMessage");
  48. config.SetSampleResponse(Sample.BatchReceiveMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchReceiveMessage");
  49. config.SetSampleResponse(Sample.DeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "DeleteMessage");
  50. config.SetSampleResponse(Sample.BatchDeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchDeleteMessage");
  51. config.SetSampleResponse(Sample.ChangeMessageVisibilityResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "ChangeMessageVisibility");
  52. // Extend the following to provide factories for types not handled automatically (those lacking parameterless
  53. // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
  54. // since automatic handling will fail and GeneratePageResult handles only a single type.
  55. #if Handle_PageResultOfT
  56. config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
  57. #endif
  58. // Extend the following to use a preset object directly as the sample for all actions that support a media
  59. // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
  60. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
  61. config.SetSampleForMediaType(
  62. new TextSample("Binary JSON content. See http://bsonspec.org for details."),
  63. new MediaTypeHeaderValue("application/bson"));
  64. //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
  65. //// and have IEnumerable<string> as the body parameter or return type.
  66. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
  67. //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
  68. //// and action named "Put".
  69. //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
  70. //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
  71. //// on the controller named "Values" and action named "Get" with parameter "id".
  72. //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
  73. //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
  74. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
  75. //config.SetActualRequestType(typeof(string), "Values", "Get");
  76. //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
  77. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
  78. //config.SetActualResponseType(typeof(string), "Values", "Post");
  79. }
  80. #if Handle_PageResultOfT
  81. private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
  82. {
  83. if (type.IsGenericType)
  84. {
  85. Type openGenericType = type.GetGenericTypeDefinition();
  86. if (openGenericType == typeof(PageResult<>))
  87. {
  88. // Get the T in PageResult<T>
  89. Type[] typeParameters = type.GetGenericArguments();
  90. Debug.Assert(typeParameters.Length == 1);
  91. // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
  92. Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
  93. object items = sampleGenerator.GetSampleObject(itemsType);
  94. // Fill in the other information needed to invoke the PageResult<T> constuctor
  95. Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
  96. object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
  97. // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
  98. ConstructorInfo constructor = type.GetConstructor(parameterTypes);
  99. return constructor.Invoke(parameters);
  100. }
  101. }
  102. return null;
  103. }
  104. #endif
  105. }
  106. }
// 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. @Html.DisplayForModel("TestClientDialogs")
  9. @Html.DisplayForModel("TestClientReferences")
  10. 添加后Api.cshtml文件的代码如下
  11. */
  12. @using System.Web.Http
  13. @using WebApiTestClient.Areas.HelpPage.Models
  14. @model HelpPageApiModel
  15. @{
  16. var description = Model.ApiDescription;
  17. ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath;
  18. }
  19. <link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
  20. <div id="body" class="help-page">
  21. <section class="featured">
  22. <div class="content-wrapper">
  23. <p>
  24. @Html.ActionLink("Help Page Home", "Index")
  25. </p>
  26. </div>
  27. </section>
  28. <section class="content-wrapper main-content clear-fix">
  29. @Html.DisplayForModel()
  30. </section>
  31. </div>
  32. @Html.DisplayForModel("TestClientDialogs")
  33. @section Scripts{
  34. <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
  35. @Html.DisplayForModel("TestClientReferences")
  36. }
/*
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")
}

最新文章

  1. Java中的Checked Exception——美丽世界中潜藏的恶魔?
  2. SQL Server 2012安装图文教程
  3. Uml学习-类图简介
  4. C#遍历指定文件夹中的所有文件和子文件夹
  5. Linux java环境安装
  6. 【转】深入理解const char*p,char const*p,char *const p,const char **p,char const**p,char *const*p,char**const p
  7. 在Salesforce中通过dataloadercliq调用data loader来批量处理数据
  8. 转:python webdriver API 之鼠标事件
  9. 11 个用来创建图形和图表的 JavaScript 工具包
  10. 浅谈Ddos攻击攻击与防御
  11. poj 1017 Packets 裸贪心
  12. VC++获取网卡MAC、硬盘序列号、CPU ID、BIOS编号
  13. .net core中引用webservice,并忽略https证书验证
  14. NIO(一)——缓冲区Buffer
  15. 用mapreduce 处理气象数据集
  16. rapidjson对于json的序列化与反序列化
  17. Linux 命令整理-ps
  18. 有道词典Linux版下载安装
  19. HP Jack介绍
  20. WebSocket——为Web应用带来桌面应用般的灵活性【转载+整理】

热门文章

  1. gen_server笔记
  2. Newtonsoft.Json 序列化反序列化
  3. 【u219】最长链
  4. [GeekBand] STL vector 查找拷贝操作效率分析
  5. Quartz 入门详解 专题
  6. boost::any在降低模块之间耦合性的应用
  7. PL/SQL一个简短的引论
  8. delphi 中的函数指针 回调函数(传递函数指针,以及它需要的函数参数)
  9. Vue 兄弟组件之间传递数值
  10. Java10 新特性