如何从ActionFilter重定向到Asp.net Core 2.2中的另一个操作或路由?

时间:2019-03-16 07:31:11

标签: asp.net-core

如何从ActionFilter重定向到Asp.net Core 2.2中的另一个控制器/动作

context.ExceptionHandled; //不显示

我已经尝试了该线程上的所有选项。 How to get filter to redirect to another action?

Redirecting to specified controller and action in asp.net mvc action filter

Redirect from exception filter

感谢您的帮助

这是我的代码

public class ValidaEmpresaActionFilter : IActionFilter
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IHttpContextAccessor _contextAccessor;

    public ValidaEmpresaActionFilter(UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor)
    {
        _userManager = userManager;
        _contextAccessor = contextAccessor; 
    }

    public async void OnActionExecuting(ActionExecutingContext context)
    {
        string username = _contextAccessor.HttpContext.User.Identity.Name;
        var user = await  _userManager.FindByNameAsync(username);

        // all options i tried Option 1
        if (user.EmpresaPrincipal == null || user.EmpresaPrincipal < 1)
        {

            RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
            redirectTargetDictionary.Add("action", "Index");
            redirectTargetDictionary.Add("controller", "Home");

            context.Result = new RedirectToRouteResult(redirectTargetDictionary);
        }
        // option #2
        if (user.EmpresaPrincipal == null || user.EmpresaPrincipal < 1)
            context.Result = new RedirectResult("~/Home/index");

        // option #3
        if (user.EmpresaPrincipal == null || user.EmpresaPrincipal < 1)
        {


            context.Result = new RedirectToRouteResult(
            new RouteValueDictionary
            {
                { "controller", "Home" },
                { "action", "Index" }
            });
        }

    }

    public void OnActionExecuted(ActionExecutedContext context)
    {

    }
}

在Startup / ConfigureServices中

        services.AddScoped<ValidaEmpresaActionFilter>();

我找到了答案==更新了**

刚刚添加了这一行 await context.Result.ExecuteResultAsync(context);

这是结果代码:

    public async void OnActionExecuting(ActionExecutingContext context)
    {
        string username = _contextAccessor.HttpContext.User.Identity.Name;
        var user = await  _userManager.FindByNameAsync(username);

        if (user.EmpresaPrincipal == null || user.EmpresaPrincipal < 1)
        {
            RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
            redirectTargetDictionary.Add("action", "Index");
            redirectTargetDictionary.Add("controller", "Home");
            redirectTargetDictionary.Add("area", "");

            context.Result = new RedirectToRouteResult(redirectTargetDictionary);
            await context.Result.ExecuteResultAsync(context);
        }             
    }

感谢所有朋友

0 个答案:

没有答案