首页 > 代码库 > asp.net web api 权限验证的方法
asp.net web api 权限验证的方法
思路:客户端使用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); //string userName = actionContext.Request.Properties["UserName"].ToString(); //string password = actionContext.Request.Properties["Password"].ToString(); //return (userName == "123" && password == "123"); } //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)); } }); }
asp.net web api 权限验证的方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。