Api控制器登录控制
1.首先先创建一个控制器:
然后在控制器中添加一个查询方法,并添加一个BaseController类
在ApiAuthorize.cs中写中断条件即可
// An highlighted block
protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
{
string RedisPrefix = System.Configuration.ConfigurationManager.AppSettings["RedisPrefix"].ToString();
try
{
var Authorization = filterContext.Request.Headers.Authorization;
byte[] bytes = Convert.FromBase64String(Authorization.Parameter);
string[] item = Encoding.Default.GetString(bytes).Split(':');
string key = $"{RedisPrefix}_{item[0]}";
FabricMunk.Cache.RedisCache cache = new FabricMunk.Cache.RedisCache();
var userToken = cache.Get<UserToken>($"{RedisPrefix}_{item[0]}");
if (userToken.Token.Equals(item[1]))
{
bool flag = Task.Run(() => cache.SaveAsync(key, userToken, new TimeSpan(720, 0, 0))).Result;
return;
}
}
catch (Exception e)
{
}
base.HandleUnauthorizedRequest(filterContext);
var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Forbidden;
response.Content = new StringContent(JsonConvert.SerializeObject(new BaseResponse<UserToken>(403, "授权未通过")), Encoding.UTF8, "application/json");
}
}
若想跳过条件,直接查询的话,只需要添加 [System.Web.Http.AllowAnonymousAttribute]就可以跳过。