简体   繁体   English

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

[英]C# API Controller Custom Filter with HttpActionContext Redirect to controller?

Is there a way to create a custom filter with an API controller to redirect to a MVC controller? 有没有一种方法可以使用API​​控制器创建自定义过滤器,以重定向到MVC控制器?

After looking around a bit his is what i have. 环顾四周后,他就是我所拥有的。

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);
    }
}

However when i execute the code it doesn't redirect them to the error page. 但是,当我执行代码时,它不会将它们重定向到错误页面。 Ideally i would like to redirect to a specify non-API controller is that possible? 理想情况下,我想重定向到指定的非API控制器吗?

I've created AuthorizeRedirectAttribute in one of my projects like this: 我在这样的一个项目中创建了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);
            }
        }
    }
}

Then I've used it like this 然后我就这样用了

[AuthorizeRedirect(Roles = "Administrator")]
public class MyController : Controller
{
}

In this case I've decorated whole controller with this attribute. 在这种情况下,我已经使用此属性装饰了整个控制器。 It can also be applied to single controller function, if necessary. 如有必要,它也可以应用于单控制器功能。 Basically what it does is, it checks whether logged on user is in role Administrator. 基本上,它会检查登录用户是否具有管理员角色。 If it is not, user is redirected to "~/Error/Forbidden403" action (returning simple view displaying user has not enough permissions). 如果不是,则将用户重定向到“〜/ Error / Forbidden403”操作(返回显示用户的简单视图没有足够的权限)。 Hope it helps. 希望能帮助到你。

You could also implement checking your own permissions, as you did in your code. 您也可以像在代码中那样实现检查您自己的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM