漂泊雪狼的博客

思考,讨论,分享C#,JavaScript,.NET,Oracle,SQL Server……技术

导航

asp.net web api 权限验证的方法

Posted on 2017-07-01 14:35  漂泊雪狼  阅读(781)  评论(0编辑  收藏  举报

思路:客户端使用header或者form讲验证信息传入api,在权限验证过滤中进行处理,代码示例:

定义过滤器

 public class ApiFilter1 : System.Web.Http.AuthorizeAttribute
    {
       
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
            //var userName = content.Request.Headers["loginName"];
               

            var user = content.Request.Form["userName"];
            var password = content.Request.Form["password"];
            //return base.IsAuthorized(actionContext);
            //return userName == "wilson" && password == "123";
            return base.IsAuthorized(actionContext);

 

        }

        //public override void OnAuthorization(HttpActionContext actionContext)
        //{
        //    var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
        //    var UserName = content.Request.Form["UserName"];

        //    //base.OnAuthorization(actionContext);
        //}

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);
        }
    }

定义api方法

 [HttpPost]
        [ApiFilter1]
        public string GetUserById2(InputPara val)
        {
            return JsonConvert.SerializeObject(val);
        }

ajax客户端调用示例

  function testAjax() {
        $.ajax({
            headers:{"loginName": "wilson", "password": "1234"},
            type: "post",
            url: "/api/user/GetUserById2",
            data: { "userName": "wilson", "password": "1234" },
            success: function (data) {
                alert(JSON.stringify(data));
            }
        });

    }

 

var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
/*
* 使用流写入的数据无法通过Form参数获取,只能通过流读取
*/
using (MemoryStream ms = new MemoryStream())
{
content.Request.InputStream.CopyTo(ms);
byte[] paraContent = ms.ToArray();
Encoding encoding = Encoding.UTF8;
string val = encoding.GetString(paraContent);
}