与HttpActionContext C#API控制器自定义过滤器重定向到控制器? [英] C# API Controller Custom Filter with HttpActionContext Redirect to controller?

查看:7792
本文介绍了与HttpActionContext C#API控制器自定义过滤器重定向到控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来创建一个API控制器自定义过滤器重定向到一个MVC控制器?

Is there a way to create a custom filter with an API controller to redirect to a MVC controller?

环视了一下之后,他的就是我。

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

然而,当我执行code它不会将其重定向到错误页面。我非常希望重定向到一个指定非API控制器是可能的吗?

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?

推荐答案

我在像这样我的项目之一创建AuthorizeRedirectAttribute:

I've created AuthorizeRedirectAttribute in one of my projects like this:

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
{
}

在这种情况下,我已经全部布置控制器此属性。它也可以在必要时施加到单个控制器功能。基本上,它是什么,它​​会检查登录的用户是否在角色管理员。如果不是,用户会被重定向到〜/错误/ Forbidden403行动(返回简单视图中显示的用户没有足够的权限)。希望它帮助。

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). Hope it helps.

您也可以实现检查你自己的权限,你在code一样。

You could also implement checking your own permissions, as you did in your code.

这篇关于与HttpActionContext C#API控制器自定义过滤器重定向到控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆