asp.net mvc 5-C#API控制器自定义过滤器与HttpActionContext重定向到控制器
本文关键字:控制器 HttpActionContext 重定向 过滤器 自定义 net mvc 5-C#API asp | 更新日期: 2023-09-27 18:01:14
是否有方法使用API控制器创建自定义过滤器以重定向到MVC控制器?
环顾四周后,他就是我的了。
public class APIHasOneOfThesePermissions : ActionFilterAttribute
{
protected UserManager<ApplicationUser> UserManager { get; set; }
private SAMPortal.DAL.SAMPortalContext db = new DAL.SAMPortalContext();
public string[] Permissions { get; set; }
public APIHasOneOfThesePermissions(string[] Permissions)
{
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));
this.Permissions = Permissions;
}
public override void OnActionExecuting(HttpActionContext filterContext)
{
string userID = HttpContext.Current.User.Identity.GetUserId();
var CurrUser = db.Users.Include(u => u.Role.Permissions).Where(user => user.Id.Equals(userID)).FirstOrDefault();
bool hasPermission = false;
foreach (string x in Permissions)
{
if (hasPermission == false)
{
hasPermission = CurrUser.HasPermission(x);
}
}
if (hasPermission == false)
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
base.OnActionExecuting(filterContext);
}
}
然而,当我执行代码时,它不会将它们重定向到错误页面。理想情况下,我想重定向到指定的非API控制器,这是可能的吗?
我在我的一个项目中创建了AuthorizeRedirectAttribute,如下所示:
using System;
using System.Net;
using System.Web.Mvc;
namespace MyNamespace.Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeRedirectAttribute : AuthorizeAttribute
{
public string RedirectUrl = "~/Error/Forbidden403";
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
var httpContext = filterContext.RequestContext.HttpContext;
var request = httpContext.Request;
var response = httpContext.Response;
// If AJAX request, just return appropriate code
if (request.IsAjaxRequest())
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
response.StatusCode = (int)HttpStatusCode.Forbidden;
else
response.StatusCode = (int)HttpStatusCode.Unauthorized;
response.SuppressFormsAuthenticationRedirect = true;
response.End();
}
// Otherwise check if authenticated, and if not redirect to specified url
if (httpContext.User.Identity.IsAuthenticated)
{
httpContext.Response.Redirect(RedirectUrl);
}
}
}
}
然后我像这个一样使用它
[AuthorizeRedirect(Roles = "Administrator")]
public class MyController : Controller
{
}
在这种情况下,我已经用这个属性装饰了整个控制器。如果需要,它也可以应用于单个控制器功能。基本上,它的作用是检查登录用户是否是管理员。否则,用户将重定向到"~/Error/Forbidden403"操作(返回显示用户权限不足的简单视图(。希望能有所帮助。
您还可以实现检查自己的权限,就像您在代码中所做的那样。