asp.net webapi 全局设置 所有api controller安全认证的方法、判断是否登录的方法
1. 新建AuthAttribute 特性
public class AuthAttribute : ActionFilterAttribute { public AuthAttribute() { } public override void OnActionExecuting(HttpActionContext actionContext) { var Context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"]; if (SkipAuth(actionContext))//是否该类标记为NoAuch { base.OnActionExecuting(actionContext); return; } //前端只要把登录成功后获取到的logintoken放入headers里传入即可。不影响正常post get的参数 var logintoken = actionContext.Request.Headers.Contains("logintoken") ? actionContext.Request.Headers.GetValues("logintoken").First() : ""; var result = Auth(logintoken); if (string.IsNullOrEmpty(logintoken) || result.Status != JsonModelHelper.EJsonModel.Auth) { Context.Response.ContentType = "application/json"; Context.Response.Write(JsonConvert.SerializeObject(new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败, 登录信息已过期,请重新登录" })); Context.Response.End();
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.NoContent); //加上这句,就不会再执行目标action了 } // base.OnActionExecuting(actionContext); }
/// <summary> /// 判断类和方法头上的特性是否要进行Action拦截 /// </summary> /// <param name="actionContext"></param> /// <returns></returns> private static bool SkipAuth(HttpActionContext actionContext) { return actionContext.ActionDescriptor.GetCustomAttributes<NoAuthAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<NoAuthAttribute>().Any(); }
}
2. 新增NoAuthAttribute 特性
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)] public class NoAuthAttribute : AuthAttribute { }
3. 在app_start/WebApiConfig.cs中配置auth过滤全局action
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 //设置全局过滤器 config.Filters.Add(new AuthAttribute()); } }
4. 设置logincontroller不判断登录状态
[NoAuth] public partial class LoginController : ApiController { /// <summary> /// 登录 /// </summary> /// <param name="adminuser">adminuser</param> /// <returns></returns> public int Post(adminuser adminuser){return 1;} }