ASP.. NET MVC 5属性路由

本文关键字:属性 路由 MVC NET ASP | 更新日期: 2023-09-27 18:11:55

我试图在MVC 5中使用路由属性。我在Visual Studio中创建了一个空的MVC项目来进行实验,到目前为止我还不能让路由工作。我用这一页作为参考。我有最新的程序集,并将所有NuGet包更新到最新版本。

下面是我的代码:

// RouteConfig.cs
namespace MvcApplication1
{
    using System.Web.Mvc;
    using System.Web.Routing;
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            // Enables MVC attribute routing.
            routes.MapMvcAttributeRoutes();
            // The default route mapping. These are "out of the bag" defaults.
            routes.MapRoute(null, "{controller}/{action}/{id}", new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            });
        }
    }
}
// TestControler.cs
namespace MvcApplication1.Controllers
{
    using System.Web.Mvc;
    public class TestController : Controller
    {
        public ContentResult Output1()
        {
            return Content("Output 1");
        }
        [Route("Test/Output2")]
        public ContentResult Test2()
        {
            return Content("Output 2");
        }
    }
}

@* Index.cshtml *@
@Html.Action("Output1", "Test")
@Html.Action("Output2", "Test")

Output1()方法正确呈现。但是,当Output2()呈现时,我得到错误"在控制器' mvcapapplication1 . controllers . testcontroller '上没有找到公共操作方法'Output2'。"

ASP.. NET MVC 5属性路由

您的操作命名为Test2而不是Output2。修改以下

@Html.Action("Test2", "Test")

这是因为@Html。Action实际上不会使用路由。有了它,你可以显式地指定动作和控制器。例如,当有人从浏览器发出http://example.org/Test/Output2请求时,路由将被使用