【问题标题】:URL Rewriting in ASP.Net MVCASP.Net MVC 中的 URL 重写
【发布时间】:2023-03-15 10:49:02
【问题描述】:

我的应用有一个基本要求:

我已经运行了基于 asp.net 平台的网站。现在我正在将我的 asp.net 应用程序转换为 asp.net mvc,但问题出现在 Url 中。我希望我的 asp.net Services.aspx 页面重定向到服务控制器

我创建了简单的 asp.net mvc 项目和下面给出的控制器:

public class ServicesController : Controller
{

    public ActionResult Index()
    {
        return View();
    }

}

请帮助我如何实现这一目标?

提前致谢。

【问题讨论】:

  • 你能解释一下吗?
  • 例如:我有一个带有 Services.aspx 页面的 asp.net 站点,它以 www.xyz.com/Services.aspx 的身份运行。现在我创建了一个新的 asp.net mvc 站点来为用户提供服务页面(www.xyz.com/Services)。现在我希望任何发送到 Services.aspx 的请求都将被重定向到 ServicesController 索引操作。

标签: asp.net-mvc-4 url-rewriting url-routing


【解决方案1】:

是的,您可以通过多种方式实现此目的。由于您使用的是 ASP.NET MVC,我建议您更改路由。

第一步是编辑 web.config 文件并添加适当的处理程序。这会将所有带有 .aspx 的文件指向TransferRequestHandler。如果您删除通配符*,您可以指定您想要处理的确切文件名(这可能不是您的需要所必需的)。你应该在<system.webServer><handlers> 标签之间添加这个:

<add name="AspxFileHandler" path="*.aspx" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

然后您将需要编辑您可以在 App_Start -> RouteConfig.cs 下找到的路由配置。如果服务器上有现有的 webform 文件,那么您需要添加:

routes.RouteExistingFiles = true;

现在添加自定义路线:

routes.MapRoute(
     name: "Services",
     url: "Services.aspx",
     defaults: new { controller = "Services", action = "Index" }
);

总而言之,您的 web.config 应该如下所示:

<system.webServer>
      <handlers>
          <add name="AspxFileHandler" path="*.aspx" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
          <remove name="BlockViewHandler"/>
          <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
      </handlers>
</system.webServer>

你的 RouteConfig 是这样的:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.RouteExistingFiles = true;

        routes.MapRoute(
          name: "Services",
          url: "Services.aspx",
          defaults: new { controller = "Services", action = "Index" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 2015-06-08
    • 2011-08-24
    • 2018-10-11
    • 2011-02-08
    • 2011-02-16
    • 2011-12-22
    • 1970-01-01
    相关资源
    最近更新 更多