Asp.net-Mvc

無法在 asp.net mvc 中為 robots.txt 映射路由

  • November 22, 2021

我正在開發一個 asp.net mvc 應用程序。我正在為我的應用程序創建 robots.txt 以防止機器人,因為我目前的站點收到了許多機器人請求。所以我找到了這個連結,MVC.NET 4 中的 Robots.txt 文件來創建 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 正確添加到我的應用程序中?

預設情況下,在 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>

引用自:https://stackoverflow.com/questions/38811358