用户登录控制器:[ActionFilter]自定义过滤器
用户信息:var userData = new JObject();
userData.Add("account", account);
userData.Add("password", password);
userData.Add("accountType",2);
生成用户登录的凭据:FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, account, DateTime.Now, DateTime.Now.AddMinutes(10),
true, JsonConvert.SerializeObject(userData), FormsAuthentication.FormsCookiePath);
string ticString = FormsAuthentication.Encrypt(ticket);
设置AJAX请求的请求头:内容为登录时生成的凭证
$.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) {
//发送ajax请求之前向http的head里面加入验证信息
xhr.setRequestHeader('Authorization', 'Basic ' + (obj.loginSession || ""));
}})
[ActionFilter]自定义过滤器:必须继承ActionFilterAttribute
public class ActionFilter : ActionFilterAttribute
{
private string _requestId;
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
//获取返回消息数据
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 = "登录已过期,请重新登录";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
new {messages = "登录已过期,请重新登录", resultCode = 1});
//HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
}
else
{
if (auther.Scheme == "Basic" && !string.IsNullOrEmpty(auther.Parameter))
{
var userData = Functions.JudgeSession(auther.Parameter.Trim());
if (userData == null)
{
//actionContext.Response.ReasonPhrase = "登录已过期,请重新登录";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
new { messages = "登录已过期,请重新登录", resultCode = 1 });
// HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
}
else
{
//修改API接口参数
actionContext.ActionArguments["account"] = userData.GetValue("account").ToString();
if (actionContext.ActionArguments.ContainsKey("accounType"))
{
actionContext.ActionArguments["account"] = userData.GetValue("accounType").ToString();
}
}
}
}}
}
解密登录凭据,获取用户数据:
public static JObject JudgeSession(string sessionid) //判断session是否过期
{
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;
}
}