前台传递一个token,后台不知道怎么获取那么不是很悲剧吗。
$(function () { $.ajax({
url: "/api/TokensTest/FirstCode",
data: {},
type: "Get",
dataType: "json",
beforeSend: function (request) {
request.setRequestHeader("Test", "woshiyanzhengma");
},
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (err) {
alert(err);
} }); });
至于token 作用就不必说了,大家都知道,要不你也不会看到这篇文章。
重点来了。我们使用 AuthorizeAttribute 这个过滤器来处理。
public class BautA : AuthorizeAttribute
{ public override void OnAuthorization(HttpActionContext actionContext)
{
var authorization = actionContext.Request.Headers.Authorization; var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
var token = content.Request.Headers["Test"]; //这里是拿到了token 的值 也就是 “woshiyanzhengma”
if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != ) { base.OnAuthorization(actionContext);//正确的访问方法 } } }
下面是如何使用
[BautA]
public class TokensTestController : ApiController
{ [HttpGet] public List<Company> FirstCode()
{ List<Company> list = new List<Company> {
new Company{id=,Name="探路者",Address="江苏南京",Phone="" },
new Company{id=,Name="探索者",Address="江苏南京",Phone="" },
new Company{id=,Name="开拓者",Address="江苏南京",Phone="" },
new Company{id=,Name="探路者",Address="江苏南京",Phone="" },
new Company{id=,Name="探路者",Address="江苏南京",Phone="" },
}; return list;
}