我在我的 asp.net webforms 3.5sp1 项目上设置了 webform 路由设置。我想将网站的文件放在一个名为 content 的目录中,包括主页,因为我想使用同一系统运行多个网站。
在 MVC 中有一个空白的默认页面,主页位于一个名为 home 的文件夹中。我似乎无法使用 Web 表单路由复制此行为,但我想这样做。空白页总是先被击中。路由处理程序是第二个——它识别出请求是针对主页的,并设置了路由页面,但未被使用。路由处理程序代码很简单:
public string VirtualPath { get; private set; }
public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
string file = requestContext.RouteData.GetRequiredString("File");
string id = requestContext.RouteData.GetRequiredString("Id");
string queryString = "?menuid=" + id;
VirtualPath = "~/" + file;
HttpContext.Current.RewritePath(
string.Concat(
VirtualPath,
queryString));
var page = BuildManager.CreateInstanceFromVirtualPath
(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
无论如何我可以做到这一点吗?
更新 这是我的 global.asax 路由代码:
public static void RegisterRoutes(RouteCollection routes)
{
Domain.RepositoryFactory repo = new RepositoryFactory();
foreach (var x in repo.MenuRepository.GetAllEnabledGetMenus())
{
if (string.IsNullOrEmpty(x.Url))
{
//add default
System.Web.Routing.RouteTable.Routes.Add(
new Route("Default.aspx",
new RouteValueDictionary(new { File = x.FileName,
Id = x.Id.ToString() }),
new CoreRouteHandler()));
}
else
{
string url = x.Url;
if(x.Url.StartsWith("/"))
{
url = url.Remove(0, 1);
}
System.Web.Routing.RouteTable.Routes.Add(
new System.Web.Routing.Route(url,
new RouteValueDictionary(new {File = x.FileName,
Id = x.Id.ToString()}),
new CoreRouteHandler()));
}
}
}
最佳答案
在我的项目中,我需要将所有调用(如 www.site.com/MyPage)重定向到/Pages/MyPage.aspx。是通过使用 HttpModule 完成的。示例代码如下:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app.Context == null || app.Context.Response == null)
return;
String sourceUrl = String.Empty;
try
{
sourceUrl = app.Request.FilePath.TrimStart('/').TrimEnd('/').ToLower();
if (global::MyProject.Global.UrlShortcuts.ContainsKey(sourceUrl))
{
String newUrl = global::MyProject.Global.UrlShortcuts[sourceUrl];
app.Context.RewritePath(newUrl, string.Empty, app.Request.QueryString.ToString(), false);
}
else
{
}
}
catch (Exception Ex)
{
// handle your exception here
}
}
次要问题是托管商的 IIS,因为我无法将其配置为使用 ASP.NET 处理所有请求。因此,我必须为在 IIS 下运行的应用程序启动时动态创建的页面(例如 www.site.com/MyPage/default.aspx)提供空白占位符 .aspx 文件。
String server = Context.Request.ServerVariables["SERVER_SOFTWARE"];
// IIS puts some stuff here, WebDev server leaves the field empty
关于c# - 在 mvc 之类的文件夹中而不是站点根目录中的 Webform 路由主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3510615/