0

我需要使用 ASP.NET 重写 URL,后面的代码为 C#。我的应用程序包含以下 URL...

http://www.mywebsite.com/Products.aspx?id=1&pg=1

但是,我需要重写 URL,以使用户在输入以下 URL 时获得与上述 URL 相同的内容...

http://www.mywebsite.com/CategoryName/ProductName/1

你们中的任何人都可以帮助我完成必要的代码吗?我的意思是 web.config、Global.asax 等...

4

2 回答 2

2

如果您有 IIS7,最好的选择是使用IIS Url Rewrite Module

于 2013-03-08T12:56:37.177 回答
0

我可以建议几个选项:

你可以看看设置一个HttpHandlerFactory.

我自己写了一个:http: //mvcsnippets.blogspot.co.uk/2012/10/custom-cms-using-httphandlerfactory.html

这是基本要点:

namespace Web.Helpers {
public class HttpCMSHandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url,string pathTranslated)
{
    string pageName = Path.GetFileNameWithoutExtension(context.Request.PhysicalPath);

    //on Server.Transfer the context is kept, so this just overrides the existing value.
    if (context.Items.Contains("PageName")) 
    {
        context.Items["PageName"] = pageName; } else { context.Items.Add("PageName", pageName); } 
        FileInfo fi = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath)); 

        //if File is not physical 
        if (fi.Exists == false) 
        {
             //return page to CMS handler the context containing "PageName" is passed on to this page, which then calls to the database to return the copy.
                return PageParser.GetCompiledPageInstance(url, context.Server.MapPath("~/CMSPage.aspx"),  context);                  
        } 
        else 
        {
            // Returns real page.
            return PageParser.GetCompiledPageInstance(context.Request.CurrentExecutionFilePath, fi.FullName, context); 
        } 
    }
}

我试图处理的行为是,如果可能有 CMS 内容,并且我不想每次需要提供信息时都创建一个页面,但是如果存在应该返回的物理页面。

对您而言,您可能希望接受 URL,将其分解为组成部分。

所以http://www.mywebsite.com/CategoryName/ProductName/1变成:

context.Items["Categoryname"] = valueFromUrlasCategoryName; 
context.Items["Productname"] = valueFromUrlasProductName; 
context.Items["Id"] = valueFromUrlasId (or pg); 

return PageParser.GetCompiledPageInstance(url, context.Server.MapPath("~/ControlPage.aspx"),  context);  

然后在您的控制页面上,您可以从传入的这些值中截取context并根据需要询问数据。

在 web.config 中,您指向 HttpHandlerFactory 的引用

<httphandlers>
<add path="*.aspx" type="Web.Helpers.HttpCMSHandlerFactory, Web.helpers" verb="*"/>
</httphandlers>

在您的情况下,您可以将路径设置为“ . ”以捕获所有流量。这意味着您必须添加对图像和脚本的处理。

您还需要确保在 IIS 中为无扩展页面添加通配符。

网上有很多关于HttpHandlerFactories的文章,可能解释得更好。

你所追求的东西是 的一部分MVC,你能看看改变你的 UI 来使用它吗?

于 2013-03-08T13:18:48.457 回答