简体   繁体   中英

ASP.NET MVC 5 Attribute Routing

I'm trying to use route attributes in MVC 5. I created an empty MVC project in Visual Studio to experiment with and so far I can't get the routing to work. I'm using this page as a reference. I have the latest assemblies and updated all NuGet packages to their latest versions.

Here's my code:

// 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")

The Output1() method renders properly. However, when Output2() is rendered, I get the error "A public action method 'Output2' was not found on controller 'MvcApplication1.Controllers.TestController'."

Your action is named Test2 not Output2 . Change the following

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

This is because @Html.Action will not actually use routing. With it you explicitly specify actions and controllers. The routing will be used when someone for instance makes the http://example.org/Test/Output2 request from a browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM