WebApi 后台获取token值

前台传递一个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(true).Count != 0 || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(true).Count != 0) { base.OnAuthorization(actionContext);//正确的访问方法 } } }

下面是如何使用

  [BautA]
    public class TokensTestController : ApiController
    {

        [HttpGet]
       
        public List FirstCode()
        {
            
            

            List list = new List {
                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;
        }

 

你可能感兴趣的:(WebApi 后台获取token值)