【问题标题】:Unable to map route for robots.txt in asp.net mvc无法在 asp.net mvc 中为 robots.txt 映射路由
【发布时间】:2016-12-13 04:12:14
【问题描述】:

我正在开发一个 asp.net mvc 应用程序。我正在为我的应用程序创建 robots.txt 以防止机器人,因为我当前的站点收到了许多机器人请求。所以我找到了这个链接,Robots.txt file in MVC.NET 4 来创建 robots.txt。但是当我像这样访问我的应用程序时,输入 url,“www.domain.com/robots.txt”,它总是返回 404 页面。

这是我在 HomeController 中的操作方法

public ActionResult Robots()
{
    Response.ContentType = "text/plain";
    return View();
}

这是我的机器人视图

@{
    Layout = null;
}

User-agent:*
Disallow:/

我在 RouteConfig 中像这样为 robots.txt 配置了路由

 public static void RegisterRoutes(RouteCollection routes)
 {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.MapMvcAttributeRoutes();
            routes.MapRoute(
               "Robots.txt",
               "robots.txt",
               new { controller = "Home", action = "Robots" },
               new string[] { "AyarDirectory.Web.Controllers" }
               );

          //other routes
}

但是当我访问这个网址“www.domain.com/robots.txt”时,它总是返回 404 页面。如何将 robots.txt 正确添加到我的应用程序中?

【问题讨论】:

  • 路径中的文件扩展名.txt 是导致您的问题的原因。
  • 但如果我像这样“机器人”映射,它不会过滤机器人。机器人总是寻找 /robots.txt。是吗?如果我排除 .txt,它还会过滤机器人吗?
  • 不,不会。你需要配置为允许robot.txt 看看这个,看看它是否有帮助stackoverflow.com/a/36151756/5233410

标签: asp.net-mvc routes asp.net-mvc-routing robots.txt


【解决方案1】:

默认情况下,在 ASP.NET MVC 中不允许创建以文件扩展名结尾的路由。要绕过此安全限制,您需要将以下内容添加到 Web.config 文件中:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- ...Omitted -->
  <system.webServer>
    <!-- ...Omitted -->
    <handlers>
      <!-- ...Omitted -->
      <add name="RobotsText"
           path="robots.txt"
           verb="GET"
           type="System.Web.Handlers.TransferRequestHandler"
           preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>

【讨论】:

    【解决方案2】:

    在 Asp.net Core 中,您只需将 robots.txt 文件添加到 wwwroot 目录即可。

    【讨论】:

      【解决方案3】:

      会说与上面相同的事情,您需要更改 web.config 以允许带有 .txt 的路由工作。我正在做的一个项目也遇到了同样的问题,我得到了它的工作。

      但是,如果您在没有模型的情况下使用视图来显示机器人的输出,则最好保留静态 robots.txt,因为它不会给您带来任何好处。另一种方法是使用字符串生成器直接从操作中输出文本。

      【讨论】:

        【解决方案4】:

        Nkosi 在 web.config 方法中的 System.Web.Handlers.TransferRequestHandler 方法由于我工作的环境对我不起作用,导致 500 错误。

        使用 web.config url 重写规则的替代方法对我有用:

        <rewrite>
            <rules>
                <rule name="Dynamic robots.txt" stopProcessing="true">
                    <match url="robots.txt" />
                    <action type="Rewrite" url="/DynamicFiles/RobotsTxt" />
                </rule>
            </rules>
        </rewrite>
        

        【讨论】:

          猜你喜欢
          • 2010-09-05
          • 1970-01-01
          • 2012-09-03
          • 2011-04-10
          • 2010-11-08
          • 1970-01-01
          • 2011-05-29
          • 1970-01-01
          • 2013-05-28
          相关资源
          最近更新 更多