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获取tokenvar 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);}}//如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401else{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{//获取数据库TokenDec.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.Sellerjo.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{//获取数据库TokenDec.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);}}
}

// 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_PageResultOfTusing 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;
#endifnamespace 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_PageResultOfTconfig.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_PageResultOfTprivate 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> constuctorType itemsType = typeof(List<>).MakeGenericType(typeParameters);object items = sampleGenerator.GetSampleObject(itemsType);// Fill in the other information needed to invoke the PageResult<T> constuctorType[] 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) constructorConstructorInfo 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")
}

源自:https://blog.csdn.net/smartsmile2012/article/details/52936011/

WebApi实现验证授权Token,WebApi生成文档等(转)相关推荐

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

    原文:WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客 [csharp] view plain copy print? using System; using System ...

  2. WebApi实现验证授权Token,WebApi生成文档等

    using System; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Security; ...

  3. showdoc如何创建文件夹_showDoc生成文档

    1. 创建项目 2. 获取api_key和api_token 1. 打开设置 2. 获取api_key和token 3. 生成文档 1. 先cd进入你的项目目录,命令行模式下输入: wget http ...

  4. 使用 apiDoc 为你的Node.js API 生成文档

    翻译: 疯狂的技术宅 原文:jonathas.com/documenting- 未经许可,禁止转载! 当你为其他开发人员(前端,桌面,移动等)开发 API 时,需要生成一份风格良好的文档,以便他们知道 ...

  5. 【飞书应用】自动生成文档

    飞书开放平台 飞书开放平台,里面有关于飞书提供的一些供开发者使用的api,可以用来开发飞书的自定义应用,本次使用里面文档相关的api来自动生成文档 创建飞书应用 可以根据飞书官方文档,创建飞书应用,本 ...

  6. apidoc生成文档时报错

    问题描述 在书写完接口的时候,使用apidoc来生成我们所需要的接口文档的时候,输入apidoc.cmd -i ./constroller -o ./doc ,其中constroller 指定读取源文 ...

  7. django集成Sphinx,为项目自动生成文档

    Sphinx是一个工具,可以轻松创建智能和漂亮的文档,他与Python自带的pydoc是同一类产品,但比pydoc更加优秀,还有很多主题可以选择,平时在开发过程中,我们看到的第三方包的文档,基本上都是 ...

  8. IDEA 版 API 接口神器来了,一键生成文档,嘎嘎香!

    先看效果,这个文档就是通过该 IDEA 插件自动生成的,你能相信吗? 文档链接:https://petstore.apifox.cn 每个开发都不想写文档.当你不想写接口文档时,可以通过安装插件在 I ...

  9. Objective-C自动生成文档工具:appledoc

    作者 iOS_小松哥 关注 2016.12.13 15:47* 字数 919 阅读 727评论 10喜欢 35 由于最近琐事比较多,所以好久没有写文章了.今天我们聊一聊Objective-C自动生成文 ...

  10. Objective-C 自动生成文档工具:appledoc

    来源:iOS_小松哥 www.jianshu.com/p/fd4d8d6b6177 如有好文章投稿,请点击 → 这里了解详情 由于最近琐事比较多,所以好久没有写文章了.今天我们聊一聊Objective ...

最新文章

  1. linux管道的执行顺序
  2. 解决python2.7 UnicodeEncodeError报错
  3. python 读帧和绘图的区别
  4. 元宇宙和游戏赚钱的兴趣正与日俱增
  5. 关于IAR的一些总结 -- ARM调试和Flash调试的区别
  6. matlab strfind用法,findstr和strfind区别
  7. android 瀑布流
  8. thinkphp手机版小说网站源码
  9. 【Elasticsearch】Elasticsearch:aggregation介绍
  10. java模拟浏览器请求HttpUtils,可秒杀京东优惠券
  11. 基于matlab的车牌识别系统设计错误,基于MATLAB的车牌识别系统设计
  12. 31.卷1(套接字联网API)---流
  13. js前端之浅拷贝与深拷贝
  14. Sublime text3 安装PyV8
  15. 中小企业生产信息化:私有系统还是云方案?
  16. 微软云服务Azure所有产品简介
  17. linux系统it固定资产管理系统包_固定资产管理系统功能介绍
  18. android手机加密失败怎么办,安卓刷机教程_安卓手机TWRP-Recovery模式图文刷机指导...
  19. C语言实现统计整数出现次数
  20. 游戏中的语音聊天方案

热门文章

  1. 计算机网络协议 | 只有程序员才能读懂的西游记 | 让我这样学习简直就是一种享受~
  2. MySql 新增数据
  3. linux系统编程实训总结,linux实训总结与体会
  4. Gradle version 和 Android Plugin Version是什么东东,有啥关系
  5. linux swap shayisi,临时邮箱,10分钟邮箱域名收集(持续更新)
  6. AlGaN/GaN HEMT 富Si的双层SiN钝化层
  7. zookeeper因内存不足造成的CPU占用率高
  8. 解决Windows Update错误“80072EFD”
  9. Android常用控件-01
  10. CTF新手抓包找flag