Webapi using filters to validate API interfaces

Source: Internet
Author: User
Tags ticket

User Login controller: [Actionfilter] Custom filter

User information: var userData = new Jobject ();
Userdata.add ("account", account);
Userdata.add ("password", password);
Userdata.add ("AccountType", 2);

Generate credentials for user logon: FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, account, DateTime.Now, DateTime.Now.AddMinutes (10),
True, Jsonconvert.serializeobject (UserData), Formsauthentication.formscookiepath);

String ticstring = Formsauthentication.encrypt (ticket);

Set the request header for an AJAX request: The credentials generated when the content is logged on

$.ajax ("/api/supervisor/getsupervisorlist", {
Method: "GET",
Data: {
Account:obj.account | | "",
loginSession:obj.loginSession | | "",
PageNo:obj.pageNo | | 1,
Keyword:obj.keyword | | ""
},//heads: {Authorization: "Basic" + obj.loginsession},
Beforesend:function (XHR) {
Add validation information to the head of HTTP before sending an AJAX request
Xhr.setrequestheader (' Authorization ', ' Basic ' + (obj.loginsession | | ""));
}})

[Actionfilter] Custom filter: must inherit ActionFilterAttribute

public class Actionfilter:actionfilterattribute
{
private string _requestid;

public override void OnActionExecuted (Httpactionexecutedcontext actionexecutedcontext)
{
Base. OnActionExecuted (ActionExecutedContext);
Get return message data
var response =

ActionExecutedContext.Response.Content.ReadAsAsync (
ActionExecutedContext.ActionContext.ActionDescriptor.ReturnType);
}
public override void OnActionExecuting (Httpactioncontext actioncontext)
{
Base. OnActionExecuting (Actioncontext);
var auther = actionContext.Request.Headers.Authorization;
if (actioncontext.actiondescriptor.getcustomattributes<allowanonymousattribute> (). Any ())
{
Return
}
if (Auther = = null)
{
ActionContext.Response.ReasonPhrase = "Login has expired, please login again";
Actioncontext.response = ActionContext.Request.CreateResponse (httpstatuscode.unauthorized,
New {messages = "Login expired, please login again", ResultCode = 1});
HttpContext.Current.Response.Redirect ("~/views/home/index.cshtml"); Skip to landing page
}
Else
{
if (auther. Scheme = = "Basic" &&!string. IsNullOrEmpty (Auther. Parameter))
{
var userData = functions.judgesession (auther. Parameter.trim ());
if (UserData = = null)
{
ActionContext.Response.ReasonPhrase = "Login has expired, please login again";
Actioncontext.response = ActionContext.Request.CreateResponse (httpstatuscode.unauthorized,
New {messages = "Login expired, please login again", ResultCode = 1});
HttpContext.Current.Response.Redirect ("~/views/home/index.cshtml"); Skip to landing page
}
Else
{

modifying API interface Parameters
actioncontext.actionarguments[' account ' = Userdata.getvalue ("account"). ToString ();
if (ActionContext.ActionArguments.ContainsKey ("Accountype"))
{

actioncontext.actionarguments["account"] = Userdata.getvalue ("Accountype"). ToString ();
}

}
}
}}
}

Decrypt the logon credentials to obtain user data:

public static Jobject judgesession (string SessionID)//Determine if session expires
{
Try
{

var FormsAuthenticationTicket = Formsauthentication.decrypt (SessionID);
if (FormsAuthenticationTicket = = null)
{
return null;
}
if (formsauthenticationticket.expired)
{
return null;
}
Return jsonconvert.deserializeobject<jobject> (Formsauthenticationticket.userdata);
}
catch (Exception e)
{
return null;
}
}

Webapi using filters to validate API interfaces

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.