ASP.NET MVC 5如何正確加入robots.txt?

ASP.NET MVC 5如何正確加入robots.txt?

robots.txt

圖片: http://blogtimenow.com

各位都知道ASP.NET MVC Framework從一開始就是走「路由(Routing)」機制,它並不是使用如ASP.NET (WebForms)的實體路徑+實體檔案的對應方式,所以要如何做才能加入robots.txt?

習慣性之Google之路

對於不知道的事物,我相信大家的第一選擇就是求Google大神幫忙。

關鍵字:mvc robots.txt

哇,有一堆的答案,都已經ASP.NET MVC 5了,這問題應該早就已經是FAQ級的問題了吧?

處理方式有二:

  • "robots.txt" Routing + ViewResult
  • "robots.txt" Routing + FileResult

"robots.txt" Routing 意指設置一條 url: "robots.txt",然後利用 default: 指到預設的 {controller}/{action},由此來回應 robots.txt 的內容。

ViewResult 是利用 View Page 來回應 robots.txt 內容。File 是利用資料流來回應 robots.txt 的內容。以效率而言,File沒有 Disk I/O 成本,是比較好的的方式,所以我最後選用File來回應 robots.txt 的內容。

以上透過一條假路由方式來模擬根目錄下的 robots.txt。

網路上的教學都還會特別提到一條 web.config 的設置:<modules runAllManagedModulesForAllRequests="true"></modules>,由 iis.net 文件中可以看到以下說明:

Optional Boolean value.

True if all managed modules can process all requests, even if the request was not for managed content; otherwise, false.

Note: In ASP.NET websites, the value of runAllManagedModulesForAllRequests previously had to be set to true to support routing. However, once IIS 7 has been updated with a Service Pack, the value of runAllManagedModulesForAllRequests can be set to false or omitted when working with ASP.NET routing. For more information, see ASP.NET Routing on the MSDN website.

The default value is false.

也就是說從 IIS 7 開始(更正確是指某個 Service Pack,我沒細查,文件也沒寫),為了支援 ASP.NET Routing ,runAllManagedModulesForAllRequests 預設會修改為 false,如果 web.cofing 沒有加上去,那麼你會得到一個 HTTP 404 錯誤。但這樣好嗎?

思考一下

就目的而言,如果你真的要用以上方式讓 ASP.NET MVC 專案可讀取 robots.txt,那麼沒有選擇,就是必須設置 runAllManagedModulesForAllRequests="true",但我越想越不對勁,我的運作環境都已經到了 IIS 8 了,但為了 robots.txt 又要封印解除(被官方修改為 false 一定有他的道理),這樣好嗎?

這時,天上有一道光,Dino大神突然出現,然後說:「信我者得 HTTP 200」。

ASP.NET MVC 5 + IIS 8 讀取 robots.txt 正確作法

請在根目錄新增 robots.txt,寫入所要設置的內容。

請在根目錄新增 robots.txt,寫入所要設置的內容。

請在根目錄新增 robots.txt,寫入所要設置的內容。

沒了,就那麼簡單。

沒有 Routing 設置,沒有 Action 方法,沒有 web.config 的 runAllManagedModulesForAllRequests 設置。

各位可以新增一個ASP.NET MVC 5專案自行測試,豬頭的我已經幫各位走過不應該走的路。網路上那條路是可以走,但當我看到Dino大神的解法之後,我就已經是他的人了(羞)。

2 則留言:

  1. FYI:
    http://blog.miniasp.com/post/2013/06/24/ASPNET-MVC-4-IIS-runAllManagedModulesForAllRequests-ExtensionlessUrlHandler.aspx

    回覆刪除

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。