WebApi 後臺獲取token值
阿新 • • 發佈:2018-11-11
前臺傳遞一個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 != 0 || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0) { base.OnAuthorization(actionContext);//正確的訪問方法 } } }
下面是如何使用
[BautA] public class TokensTestController : ApiController { [HttpGet] public List<Company> FirstCode() { List<Company> list = new List<Company> { new Company{id=1,Name="探路者",Address="江蘇南京",Phone="15996413689" }, new Company{id=2,Name="探索者",Address="江蘇南京",Phone="15996413689" }, new Company{id=3,Name="開拓者",Address="江蘇南京",Phone="15996413689" }, new Company{id=4,Name="探路者",Address="江蘇南京",Phone="15996413689" }, new Company{id=5,Name="探路者",Address="江蘇南京",Phone="15996413689" }, }; return list; }