我有以下路线
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Hotel", "en/hotels/{*hotelName}",
new { controller = "Hotel", action = "index" });
}
所以下面的 URL 被路由
www.mydomain.com/en/hotels/my-hotel-name/
www.mydomain.com/en/hotels/myhotelname/
www.mydomain.com/en/hotels/my_hotel_name/
在我的 Controller 中,我有条件检查以查看传递的 URL 是否存在于我的查找表中。例如
public class HotelController : Controller
{
[HttpGet]
[ActionName("Index")]
public ActionResult IndexGet(string hotelFolder)
{
if(CheckIfFolderExists(hotelFolder))
{
return Content("Hotel URL Found");
}
else
{
**//Here, I want to return the actual requested URL as it didn't exist in my lookup table
}
}
}
路由根据 en/hotels 路径工作,如果像下面这样输入了错误的 URL,则实际的 URL 会像正常情况一样返回。
www.mydomain.com/en/attractions/my-attraction-name/
基本上,我想建立一个我想要路由的 URL 字典,如果字典中不存在请求的 URL,我想返回请求的 URL,无论是 .HTM、.HTML 还是.ASP 页面。
最佳答案
我不完全理解你的问题,但如果你想在你定义的路由之外提供静态 html 文件,你可以有一个 public 或 static 文件夹并允许访问 html 文件。
您可以通过在该文件夹中创建一个 Web.config 文件并注册处理程序来完成此操作:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<handlers>
<add name="HtmScriptHandler" path="*.htm" verb="GET"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<add name="HtmlScriptHandler" path="*.html" verb="GET"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
然后,任何 .htm 或 .html 文件都将在请求时提供。
关于c# - 如何在 MVC 中路由特定的 URL,否则返回请求的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56084932/