【问题标题】:Route Static URL to Controller action in MVC?将静态 URL 路由到 MVC 中的控制器操作?
【发布时间】:2015-05-27 12:36:04
【问题描述】:

大家好,我的控制器中有一个 aciton,它为我的站点生成站点地图,这里的问题是第一次当文件不存在时,请求转到操作 但是一旦生成文件,就会在站点中放置一个静态文件,之后当我点击 URL 时,请求不会发送到控制器,是否有解决此问题的方法

Below is the URL

        http://localhost:1234/sitemap.xml

Below is the code am using

        [HttpGet, ActionName("sitemap")]
        public ActionResult sitemap()
        {           

           //will get the sitemap content here and will generate the sitemap 
            var sitemapFile = "~/sitemap.xml";
            return File(sitemapFile, "text/xml");
        }

每次我点击 URL 时,它都应该执行操作并重新生成文件,但这在这里不起作用,任何人都可以帮助我

【问题讨论】:

  • @SHammelburg 是的,可以,但我希望它以这种方式工作,因为我们必须将其提交给带有 sitemap.xml 扩展名的谷歌机器人,这就是我必须编写自定义路线的原因

标签: c# asp.net-mvc-5 asp.net-mvc-routing


【解决方案1】:

当您的 sitemap.xml 文件存在时,IIS 将接收请求并为您现有的 sitemap.xml 提供服务。有关此事的更多信息,请查看this article

如果我理解正确,您想将sitemap.xml requests 路由到MVC route,这很好blog post

首先需要将sitemap.xml的请求映射到TransferRequestHandler。将此添加到您的 web.config 中

<add name="SitemapFileHandler" path="sitemap.xml" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

接下来在 RouteConfig.cs 中配置路由:

routes.MapRoute(
    name: "SiteMapRoute",
    url: "sitemap.xml",
    defaults: new { controller = "SEO", action = "Sitemap", page = UrlParameter.Optional }
);

并在您映射任何路线之前将此声明

routes.RouteExistingFiles = true;

更多关于RouteExistingFiles的信息

【讨论】:

  • 安德鲁,我们在哪里需要节 .config 文件,什么是“SitemapFileHandler”
  • 我猜你的意思是在哪里添加 SiteMapFilHandler ?这需要在 节点中的 web.config 中
【解决方案2】:

你能试试这个自定义路线吗,

将其添加到您的 RouteConfig.cs 文件中

routes.MapRoute(
    name: "Sitemap",
    url: "Sitemap",
    defaults: new { controller = "Home", action = "Sitemap" }
);

您可以像这样访问您的操作,

http://localhost:1234/sitemap

希望它是您想要的。

【讨论】:

  • 当我使用 URL "localhost:1234/sitemap" 时这个肯定会起作用,但我也希望它在 URL 是 "localhost:1234/sitemap.xml" 时起作用
  • 如果您的根文件夹中有 sitemap.xml,那么它应该可以工作。我刚刚尝试过并加载了两种方式。
  • 是的,它会加载,但是一旦文件存在,它就永远不会再次执行该操作,直到文件被删除
  • 你是如何创建 sitemap.xml 的?
猜你喜欢
  • 1970-01-01
  • 2015-11-18
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多