从MVC控制器重定向到另一个episerver页面?

时间:2014-03-11 13:24:59

标签: asp.net-mvc episerver

如何从Episerver中的任何MVC控制器重定向到任何页面(例如Home)?例如,登录后 - 重定向到起始页面。

4 个答案:

答案 0 :(得分:10)

重定向到任何MVC操作:

public ActionResult Index()
{
    return RedirectToAction("Index", "Home");
}

重定向到网站的已配置起始页:

public ActionResult Index()
{
    PageData startPage =
        ServiceLocator.Current.GetInstance<IContentRepository>().Get<PageData>(ContentReference.StartPage);

    // get URL of the start page
    string startPageUrl = ServiceLocator.Current.GetInstance<UrlResolver>()
                .GetVirtualPath(startPage.ContentLink, startPage.LanguageBranch);

    return Redirect(startPageUrl);
}

答案 1 :(得分:10)

您实际上仍然可以将RedirectToAction与EPiServer配合使用,只要您还提供该页面的内容参考。

public ActionResult Index()
{
    return RedirectToAction("ActionName", new { node = ContentReference.StartPage });
}

已在EPiServer 7.5.440.0中测试过。

答案 2 :(得分:2)

您可以使用RedirectToAction()重定向到特定操作或Redirect()到特定URL。在ASP.NET MVC 4中,您可以使用RedirectToLocal()而不是Redirect(),出于安全原因,当您使用查询字符串中的参数时,建议使用此方法。

public ActionResult MyAction()
{
    // Use this for an action
    return RedirectToAction("Action");
    // Use this for a URL
    return Redirect("/"); // (Website root)
    // Use this for a URL within your domain
    return RedirectToLocal("/"); // (Website root)
}

有关详细信息,请参阅以下链接:

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction(v=vs.118).aspx http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirect(v=vs.118).aspx

答案 3 :(得分:0)

在EpiServer 11中,我发现使用依赖注入更加清晰,而不是像Thomas Krantz所建议的那样使用ServiceLocator。

使用依赖注入的示例:

public class SomeController 
{
   private readonly IContentLoader _contentLoader;
   private readonly UrlResolver _urlResolver;

   public SomeController(IContentLoader contentLoader, UrlResolver urlResolver)
   {
     _contentLoader = contentLoader ?? throw new ArgumentNullException(nameof(contentLoader));
     _urlResolver = urlResolver ?? throw new ArgumentNullException(nameof(urlResolver));
   }

   public ActionResult Index(SomePage currentPage)
   {
     //Retrieving an example startpage type
     var startPageContentLink =_contentLoader.Get<StartPageType>(ContentReference.StartPage);
     //Getting the redirect link -> Type: VirtualPathData
     var redirectLink = urlResolver.GetVirtualPath(startPageContentLink);

     return Redirect(redirectLink.VirtualPath);
   }
}

当使用内容加载器时,自然会缺少一些验证(如果您的给定StartPageType不存在,它可能会抛出异常)。