如何在Asp.Net WebApi接口中,验证请求参数中是否携带token标识!
[BasicAuthentication]
public abstract class ApiControllerBase : ApiController
{
#region Gloal Property
/// <summary>
/// token_id
/// </summary>
public string token_ID { get; set; } /// <summary>
/// user_id
/// </summary>
public string user_ID { get; set; }
#endregion #region InitializeUser
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
user_ID = token_ID = string.Empty; #region 【 验证请求中是否有 token 授权 】
if (controllerContext.Request.Method != HttpMethod.Get)
{
string postContentData = string.Empty;
string contentType = string.Empty;
string postTokenStr = string.Empty;
//----------------获取Post参数--------------------
NameValueCollection postParam = null; //【处理】content-type:application/x-www-form-urlencoded
if (controllerContext.Request.Content.IsFormData())
{
postParam = controllerContext.Request.Content.ReadAsFormDataAsync().Result;
postContentData = postParam.ToString();
postTokenStr = postParam["token"] ?? "";
contentType = "application/x-www-form-urlencoded";
}
//【处理】 content-type:application/json
else
{
contentType = "application/json";
if (!controllerContext.Request.Content.IsMimeMultipartContent("form-data"))
{
postContentData = controllerContext.Request.Content.ReadAsStringAsync().Result;
JavaScriptSerializer json = new JavaScriptSerializer();
dynamic token = json.Deserialize(postContentData, typeof(object));
if (postContentData.Contains("token"))
{
postTokenStr = Convert.ToString(token["token"]);
}
}
else
{
contentType = "multipart/form-data";
var collPostParamData = controllerContext.Request.RequestUri.ParseQueryString();
//----------------同时处理Post中的Url参数请求-------------------------------
if (!string.IsNullOrWhiteSpace(collPostParamData["token"]))
{
postTokenStr = System.Web.HttpUtility.UrlDecode(collPostParamData["token"]);
}
}
}
//----------------设置回FormData参数----------------------
if (!controllerContext.Request.Content.IsMimeMultipartContent("form-data"))
{
StringContent content = new StringContent(postContentData, Encoding.UTF8, contentType);
controllerContext.Request.Content = content;
} this.token_ID = postTokenStr;
BasicAuthenticationAttribute.isLoginAuth = ValidateCacheToken(postTokenStr);
}
else
{
var getParam = controllerContext.Request.RequestUri.ParseQueryString();
//----------------Get请求-------------------------------
if (!string.IsNullOrWhiteSpace(getParam["token"]))
{
var _getToken = System.Web.HttpUtility.UrlDecode(getParam["token"]);
this.token_ID = _getToken;
BasicAuthenticationAttribute.isLoginAuth = ValidateCacheToken(_getToken);
}
}
#endregion
base.Initialize(controllerContext);
}
注意: controllerContext.Request.Content.ReadAsFormDataAsync().Result 和 controllerContext.Request.Content.ReadAsStringAsync().Result; 只能取,并且取完,后面子类中就获取不到了,必须就得重新赋值进去,这是我觉得很怪异的地方。
StringContent content = new StringContent(postContentData, Encoding.UTF8, contentType);
controllerContext.Request.Content = content;
如何在Asp.Net WebApi接口中,验证请求参数中是否携带token标识!的更多相关文章
- Asp.Net WebAPI 通过HttpContextBase获取请求参数
WEBAPI中的Request是HttpRequestMessage类型,不能像Web传统那样有querystring和from 方法接收参数,而传统的HttpReqest的基类是HttpReqest ...
- 使用@Valid和BindingResult验证请求参数的合法性并处理校验结果
/** * 添加用户,使用@RequestBody将请求体映射到Action方法参数中 * 使用@Valid注解验证请求参数的合法性 * 使用BindingResult处理校验结果 * @param ...
- ASP.NET WEBAPI 的身份验证和授权
定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...
- asp.net webapi 自定义身份验证
/// <summary> /// 验证 /// </summary> /// Account API账号 /// TimeStamp 请求时间 /// Sign 所有请求参数 ...
- ASP.NET WebApi OWIN 实现 OAuth 2.0(自定义获取 Token)
相关文章:ASP.NET WebApi OWIN 实现 OAuth 2.0 之前的项目实现,Token 放在请求头的 Headers 里面,类似于这样: Accept: application/jso ...
- 关于ASP.NET Web API 客户端的请求报文中添加 Authorization
当你使用客户端发送请求 Web API 的时候,因为API 有验证,所以你的请求报文中必须有”Authorization“,那么就需要手动添加了! HttpClient client = new Ht ...
- hibernate-validator验证请求参数
开发接口要进行请求参数内容格式校验,比如在接收到请求参数后依次需要进行数据内容判空.数据格式规范校验等,十分麻烦,于是尝试用hibernate-validator进行参数校验,简单记录一下使用步骤: ...
- Springboot采用hibernate-validate验证请求参数
在springboot项目使用hibernate-validate对请求参数添加注解进行校验 常用注解 @Null,标注的属性值必须为空 @NotNull,标注的属性值不能为空 @AssertTrue ...
- nodejs获取ASP.Net WebAPI(IIS Windows验证)
处理了很多天,终于使用Nodejs可以发出请求至WebAPI,能够正常处理数据了 首先加入npm包 npm install httpntlm 在app.js中加入代码 var httpntlm = r ...
随机推荐
- 【BZOJ】【3093】【FDU校赛2012】A Famous Game
概率论 神题不会捉啊……挖个坑先 orz 贾教 & QuarterGeek /********************************************************* ...
- [设计模式] 7 桥接模式 bridge
#include<iostream> using namespace std; class AbstractionImp { public: virtual ~AbstractionImp ...
- jquery 实现层级下拉框联动效果 代码
<select name="fCareId" id="fCareId"> <option selected="selected&qu ...
- PHP7 扩展之自动化测试
在安装 PHP7 及各种扩展的过程中,如果你是用源码安装,会注意到在 make 成功之后总会有一句提示:Don't forget to run 'make test'. 这个 make test 就是 ...
- 【设计模式六大原则3】依赖倒置原则(Dependence Inversion Principle)
定义:高层模块不应该依赖低层模块,二者都应该依赖其抽象:抽象不应该依赖细节:细节应该依赖抽象. 问题由来:类A直接依赖类B,假如要将类A改为依赖类C,则必须通过修改类A的代码来达成.这种场景下,类 ...
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- 学习笔记--Git安装 创建版本库 图文详解
一.Git下载 在Windows上安装git,一般为msysgit,官网地址:http://git-scm.com/ 我下载的是Git-1.9.2-preview20140411.exe 二.Git安 ...
- java基础知识回顾之java Socket学习(一)--UDP协议编程
UDP传输:面向无连接的协议,不可靠,只是把应用程序传给IP层的数据报包发送出去,不保证发送出去的数据报包能到达目的地.不用再客户端和服务器端建立连接,没有超时重发等机制,传输速度快是它的优点.就像寄 ...
- Test Markdown Editor
Last night, I just saw a cute blogger's homepage. Then I want to write something. But anyway, I use ...
- http://www.cnblogs.com/huangcong/archive/2010/06/14/1757957.html
http://www.cnblogs.com/huangcong/archive/2010/06/14/1757957.html http://www.cnblogs.com/langtianya/a ...