WebApi过滤器1
public class TestController : ApiController
{
///
/// 名称
///
[CustAuthorize]
public ResultInfo GetUserInfo(int num)
{
List
new List
new UserInfoViewModel() { Email="782323@qq.com",HasRegistered=false,LoginProvider="33d"}
};
return new ResultInfo(){Status="100", Message = "",Data=list };
}
///
/// 参数2
///
[CustAuthorize]
[System.Web.Http.HttpPost]
public ResultInfo GetUserInfo2()
{
List
new List
new UserInfoViewModel() { Email="782323@qq.com",HasRegistered=false,LoginProvider="33d"}
};
return new ResultInfo() { Status = "100", Message = "", Data = list };
}
}
///
public class CustAuthorizeAttribute : AuthorizeAttribute
{
//判断权限
///
///
///
protected override bool IsAuthorized(HttpActionContext actionContext)
{
string[] rolelist = { "102", "103", "104", "105", "106" };
var queryString = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
var myQueryParam = queryString["roles"];
if (rolelist.Contains(myQueryParam))
{
return true;
}
else
{
return false;
}
}
//权限为false执行内容
///
///
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
base.HandleUnauthorizedRequest(actionContext);
}
WebApi过滤器2
MVC过滤器
public class TestController : Controller
{
[CustAuthorize("102")]
public ActionResult List()
{
return View();
}
}
public class CustAuthorizeAttribute : AuthorizeAttribute
{
public String[] roles;
public CustAuthorizeAttribute(params String[] role)
{
roles = role;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
String role = "1012";
bool b = roles.Contains(role);
return b;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.HttpContext.Response.Write("");
}
}
MVC登录验证
public class UserAuthenAttribute : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
var user = Cache.ReourseRedis.GetUserIfo();
var url = filterContext.HttpContext.Request.Url.ToString();
if (user==null && url.IndexOf("Login")<0)
{
filterContext.Result = new RedirectResult("/Test/Login");
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
}
}
全局错误信息
namespace WebApplication1.App_Start
{
public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new ResultInfo() { Status = "102", Message = "error" }));
context.Response = response;
base.OnException(context);
}
}
}
Glob文件=》
GlobalConfiguration.Configuration.Filters.Add(new ApiExceptionFilterAttribute());
手机扫一扫
移动阅读更方便
你可能感兴趣的文章