1.在Ajax请求时,添加Header
$.ajax({
type: "Post",
url: path,
beforeSend: function (xhr) {
//发送ajax请求之前向http的head里面加入验证信息
xhr.setRequestHeader("accessToken", "123456"); // 请求发起前在头部附加token
},
...
...
...
});
2.在Web.config文件中配置webServer属性
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<!--响应头 请按照自己需求添加 这里新加了token这个headers-->
<add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With,accessToken" />
</customHeaders>
</httpProtocol>
</system.webServer>
3.在ASP的WebMethod中取得Token
[WebMethod]
public static string[] GetInfos()
{
string accessToken = HttpContext.Current.Request.Headers.Get("accessToken");
//这里就取得请求时的Token值了。
}
注意:如果上面的方式还是取不到请求头中的Token值,就清空一下浏览器的本地Cookies等缓存,因为请求头是一般被缓存的。然后再试一下就OK啦。祝你们好运。