Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 更改ASP.NET MVC筛选器中的视图_Asp.net Mvc_Asp.net Mvc 3_Filter - Fatal编程技术网

Asp.net mvc 更改ASP.NET MVC筛选器中的视图

Asp.net mvc 更改ASP.NET MVC筛选器中的视图,asp.net-mvc,asp.net-mvc-3,filter,Asp.net Mvc,Asp.net Mvc 3,Filter,如果用户使用移动浏览器,我想将其重定向到其他视图。我决定使用MVC过滤器来实现这一点,将其应用于我希望具有移动视图的操作 我相信这种重定向需要在OnActionExecuted中发生,但是filterContext不包含视图的信息-它确实包含,但是在OnResultExecuted中,但是我认为现在更改视图已经太晚了 如何截取视图名称并更改ViewResult 这就是我在结果中执行的内容,也是我希望执行工作的内容 public class MobilePageFilter : ActionFil

如果用户使用移动浏览器,我想将其重定向到其他视图。我决定使用MVC过滤器来实现这一点,将其应用于我希望具有移动视图的操作

我相信这种重定向需要在OnActionExecuted中发生,但是filterContext不包含视图的信息-它确实包含,但是在OnResultExecuted中,但是我认为现在更改视图已经太晚了

如何截取视图名称并更改ViewResult

这就是我在结果中执行的内容,也是我希望执行工作的内容

public class MobilePageFilter : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if(filterContext.Result is ViewResult)
        {
            if (isMobileSite(filterContext.HttpContext.Session[SetMobile.SESSION_USE_MOBILE]))
            {
                ViewResult viewResult = (ViewResult)filterContext.Result;

                string viewName = viewResult.ViewName;
                filterContext.Result = new ViewResult
                {
                    ViewName = "Mobile/" + viewName,
                    ViewData = viewResult.ViewData,
                    TempData = viewResult.TempData
                };
            }
        }

        base.OnResultExecuted(filterContext);
    }
}

我建议您使用,这解释了一个更好的替代方案,以实现您的要求,而不是使用操作过滤器。

这就是我最后所做的,并包装成一个可重用的属性,最棒的是它在重定向(或应用任何您希望的结果)时保留原始URL根据您的要求:

public class AuthoriseSiteAccessAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // Perform your condition, or straight result assignment here.
        // For me I had to test the existance of a cookie.
        if (yourConditionHere)
            filterContext.Result = new SiteAccessDeniedResult();
    }

}

public class SiteAccessDeniedResult : ViewResult
{
    public SiteAccessDeniedResult()
    {
        ViewName = "~/Views/SiteAccess/Login.cshtml";
    }
}

然后,只需将属性
[SiteAccessAuthorization]
添加到您希望对其应用授权访问的控制器(在我的情况下)或将其添加到BaseController。确保您重定向到的操作的底层控制器没有该属性,否则您将陷入无休止的循环

在Global.cs中添加路由规则