使用HttpActionContext的C#API控制器自定义过滤器重定向到控制器?

时间:2015-07-06 22:23:27

标签: c# asp.net-mvc-5 asp.net-mvc-custom-filter

有没有办法使用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控制器是可能的吗?

1 个答案:

答案 0 :(得分:1)

我在我的一个项目中创建了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
{
}

在这种情况下,我用这个属性装饰了整个控制器。如有必要,它还可以应用于单个控制器功能。基本上它的作用是,它检查登录用户是否在角色管理员中。如果不是,则将用户重定向到&#34;〜/ Error / Forbidden403&#34; action(返回显示用户的简单视图没有足够的权限)。希望它有所帮助。

您也可以像在代码中一样实现检查自己的权限。