在Global.asax中设置MasterPageFile会破坏URL页面路由

时间:2014-06-17 16:00:24

标签: c# asp.net url-routing master-pages

我使用Global.asax文件覆盖Page_PreInit事件以设置MasterPageFile,我也使用Page Routing

似乎当我设置MasterPageFile时,它会中断PageRouting并在每个网址上生成404.

void Application_PreRequestHandlerExecute(object src, EventArgs e)
{
    Page p = this.Context.Handler as Page;
    if (p != null) {
        p.PreInit += new EventHandler(Page_PreInit);
    }
}

void Page_PreInit(object sender, EventArgs e)
{
    Page p = this.Context.Handler as Page;
    if (p != null) {
        if (HttpContext.Current.Session["Branding-UseCustomMasterPage"] != null && HttpContext.Current.Session["Branding-CustomMasterPageName"] != null) {
            if (Boolean.Parse(HttpContext.Current.Session["Branding-UseCustomMasterPage"].ToString())) {
                if (Request.UserAgent.Contains("Valve Steam GameOverlay")) {
                    p.MasterPageFile = "~/APIMasterPages/" + HttpContext.Current.Session["Branding-CustomMasterPageName"].ToString() + "-SteamOverlay.master";
                }
                else {
                    p.MasterPageFile = "~/APIMasterPages/" + HttpContext.Current.Session["Branding-CustomMasterPageName"].ToString() + ".master";
                }
            }
        }
        else {
            if (Request.UserAgent.Contains("Valve Steam GameOverlay")) {
                p.MasterPageFile = "~/APIMasterPages/SteamOverlay.master";
            }
        }
    }
}

用于设置PageRoutes的代码是:

protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.Ignore("");

    routes.MapPageRoute("api-initiate", "api-initiate/{apiKey}/", "~/Corporate/APIInitiate.aspx");

    routes.MapPageRoute("404", "{*url}", "~/Page-Not-Found.aspx");
}

2 个答案:

答案 0 :(得分:0)

你试图从会话中拉出的所有对象是否都是空的,而你只是在你的Page_PreInit()中遇到了else {}的情况?

答案 1 :(得分:0)

找出问题所在;在Page_Load,我正在与MasterPage进行互动;

SiteMaster m = Master as SiteMaster;

然而,当我更改了导致错误的MasterPage时;并且PageRoute发送了404错误。

修复是使用我在MasterPage类中继承的实际类。

Custom.CustomMasterPage m = Master as Custom.CustomMasterPage;

MasterPage类定义:

public partial class SiteMaster : Custom.CustomMasterPage
{ 
    // Master page class   
}