gpt4 book ai didi

c# - 在 ASP.NET MVC 中使用破折号进行路由

转载 作者:行者123 更新时间:2023-11-30 15:28:22 24 4
gpt4 key购买 nike

我正在使用 ASP.NET MVC 5 开发应用程序。我希望我的应用程序具有如下所示的路由:

http://www.myserver.com/my-category

请注意 route 有破折号 (-)。我目前有一个名为 MyCategoryController 的 Controller 。它是这样定义的:

namespace MyApp.Controllers
{
[RoutePrefix("my-category")]
public class MyCategoryController : Controller
{
// GET: List
public ActionResult Index()
{
return View();
}
}
}

View 位于 /Views/My-Category/Index.cshtml。当我尝试在浏览器中访问 http://www.myserver.com/my-category 时,我收到一条错误消息:

The resource cannot be found.

我设置了一个断点,我注意到断点没有命中。然后我输入 http://www.myserver.com/mycategory进入浏览器,我收到一条错误消息:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/mycategory/Index.cshtml
~/Views/mycategory/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

如何设置我的 ASP.NET MVC 以便
a) 我可以访问 http://www.myserver.com/my-category
b) 从 /Views/my-category/Index.cshtml

加载 View

最佳答案

你需要像 Controller 一样命名 views 文件夹而不是路由。

所以 /Views/MyCategory/Index.cshtml 而不是 /Views/My-Category/Index.cshtml

如果出于某种我无法想象的原因,你希望它成为/Views/My-Category/Index.cshtml,你需要“完全限定 View ”:

return View("~/Views/My-Category/Index.cshtml");

关于带破折号的路由:我没有使用基于属性的路由,所以我只能猜测:
您是否在 RegisterRoutes 方法中添加了 routes.MapMvcAttributeRoutes();
因为 http://www.myserver.com/mycategory 是由默认的 "{controller}/{action}/{id}" 路由...

关于c# - 在 ASP.NET MVC 中使用破折号进行路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25891169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com