无法在asp.net mvc

时间:2016-08-07 05:58:28

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

我正在开发一个asp.net mvc应用程序。我正在为我的应用程序创建robots.txt以防止机器人,因为我当前的站点收到了很多机器人请求。所以我找到了这个链接,Robots.txt file in MVC.NET 4来创建robots.txt。但是当我访问我的应用程序时,如此输入网址“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添加到我的应用程序中?

3 个答案:

答案 0 :(得分:4)

默认情况下,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>

答案 1 :(得分:1)

如上所述,你需要更改web.config以允许带有.txt的路由工作。我对我正在进行的项目遇到了同样的问题,我让它开始工作。

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

答案 2 :(得分:0)

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

enter image description here