WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客
原文:WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客
- 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;
- }
- }
- }
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;
}
}
}
- 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
- }
- }
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
}
}
- //////////////////////////////////////////////////////////////////
- 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);
- }
- }
- }
//////////////////////////////////////////////////////////////////
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);
}
}
}
- // 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
- }
- }
// 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
}
}
- /*
- 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")
- }
/*
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")
}
WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客的更多相关文章
- WebApi实现验证授权Token,WebApi生成文档等
using System; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Security; ...
- WebApi实现验证授权Token,WebApi生成文档等(转)
using System; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Security; ...
- 使用swagger在netcorewebapi项目中自动生成文档
一.背景 随着前后端分离模式大行其道,我们需要将后端接口撰写成文档提供给前端,前端可以查看我们的接口,并测试,提高我们的开发效率,减少无效的沟通.在此情况下,通过代码自动生成文档,这种需求应运而生,s ...
- 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)
对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战.在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你 ...
- ASP.NET Core 1.0 中使用 Swagger 生成文档
github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...
- MVC WEB api 自动生成文档
最近在一直在用webapi做接口给移动端用.但是让我纠结的时候每次新加接口或者改动接口的时候,就需要重新修改文档这让我很是苦恼.无意中发现.webapi居然有自动生成文档的功能....真是看见了救星啊 ...
- REST开放接口生成文档工具之apidoc
一.安装node.js环境 感谢阿里云,下载的链接http://npm.taobao.org/mirrors/node/latest-v6.x/ 二.安装apidoc npm install apid ...
- 使用Ldoc给Lua生成文档
Ldoc介绍 LDoc是一个Lua的文档生成工具,过去,比较常用的Lua生成文档的工具是LuaDoc,可惜作者自从2008年之后就再也没有发布过新的版本了,说明作者基本上已经放弃维护了.而LDoc则是 ...
- 使用PhpDocumentor生成文档
一,网站根目录执行 $ composer require --dev phpdocumentor/phpdocumentor 二,进入vendor/bin/目录执行 $phpdoc -d D:\ser ...
随机推荐
- 详细回复某个CSDN网友,对我的文章和技术实力以及CSDN的吐槽
貌似被大学生鄙视了,我也是醉了,现在的大学生水平和信心,都这么高了~ 看来,我得加把劲了~ o(︶︿︶)o 电子商务系列文章,是我闲来无事,分享自己的一些业余实践经验的文章.其中关于数据库设计的这一篇 ...
- 简洁常用权限系统的设计与实现(六):不维护节点的深度level,手动计算level,构造树 (把一颗无序的树,变成有序的)
本篇介绍的方法,参考了网上的代码.在递归过程中,计算level,是受到了这种方法的启发. CSDN上有篇关于树的算法,目标是把一个无序的树,变成有序的. 我看了下代码,并运行了下,感觉是可行的. 我 ...
- Zepto.js touch,tap增加 touch模块深入分析
1. touch库实现了什么和引入背景 click事件在移动端上会有 300ms 的延迟,同时因为需要 长按 , 双触击 等富交互,所以我们通常都会引入类似 zepto 这样的库.zepto 中tou ...
- 【record】10.30..11.6
越做越少..
- hadoop 3.x Replication与Availability不一致
看下面的文字前先确保你的Replication值不大于你设置的虚拟机数量 如图,显示的副本数为3,但是实际可用的只有一台机器,查看了下hadoop003,hadoop004两台机器,果然没有存储数据, ...
- python3第一天学习(数据类型)
参考blog地址:http://www.cnblogs.com/wupeiqi/articles/5444685.html,然后根据上面知识点练习并总结. 一.数字(int) 1.数字类型说明 在 ...
- JSP和Servlet学习笔记1 - 访问配置
1. 访问 WebContent 目录下的 JSP 文件 在 WebContent 目录下的文件可以直接在浏览器中访问.新建一个 test.jsp 文件 <%@ page language=&q ...
- 获取当前div中的所有div的个数和每一个div的ID and 根据屏幕分辨率计算高度
var tabs_Count=document.getElementById("tabs-panels").getElementsByTagName("div" ...
- 阿里云CentOS7系统搭建JavaWeb环境
一,准备工作 1,安装目录 我们创建如下路径/usr/develop,然后在develop目录下面创建java,tomcat和mysql三个目录即可. 二,配置JDK 1.理解wget命令 wget命 ...
- C#连接Oracle数据库乱码问题
C#连接Oracle数据库乱码问题 数据库连接之前,设置环境变量,如下 Environment.SetEnvironmentVariable("NLS_LANG", "A ...