Idea: The client uses the header or form to verify that the information is passed into the API and is processed in the permission validation filter, code example:
Defining filters
Public classApiFilter1:System.Web.Http.AuthorizeAttribute { protected Override BOOLisauthorized (Httpactioncontext actioncontext) {varContent = actioncontext.request.properties["Ms_httpcontext"] asHttpContextBase; //var userName = content. request.headers["LoginName"]; varuser = content. request.form["UserName"]; varPassword = 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 voidhandleunauthorizedrequest (Httpactioncontext actioncontext) {Base. Handleunauthorizedrequest (Actioncontext); } }
Defining API Methods
[HttpPost] [ApiFilter1] Public string GetUserById2 (Inputpara val) { return Jsonconvert.serializeobject (val); }
AJAX Client Invocation Example
function Testajax () { $.ajax ({ headers:{"LoginName": "Wilson", "Password": "1234"}, "POST" , " /api/user/getuserbyid2 ", " UserName ":" Wilson "," Password ":" 1234 " }, function (data) { alert (json.stringify (data)); } ); }
Methods of ASP. NET Web API permission validation