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

时间:2022-06-22 03:52:32

思路:客户端使用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 权限验证的方法