ASP.NET MVC 5属性路由

Hal*_*yon 0 c# asp.net-mvc visual-studio

我正在尝试在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")
Run Code Online (Sandbox Code Playgroud)

Output1()方法正确呈现.但是,当渲染Output2()时,我得到错误"在控制器'MvcApplication1.Controllers.TestController'上找不到公共操作方法'Output2'."

Cha*_*own 8

你的行动Test2不是Output2.更改以下内容

@Html.Action("Test2", "Test")
Run Code Online (Sandbox Code Playgroud)

  • 您可以根据需要为路径命名,但是`Html.Action`方法参数基于控制器中的实际方法名称. (3认同)