簡體   English   中英

ASP.NET MVC 5屬性路由

[英]ASP.NET MVC 5 Attribute Routing

我正在嘗試在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()時,出現錯誤“在控制器'MvcApplication1.Controllers.TestController'上未找到公共動作方法'Output2'”。

您的操作名為Test2而不是Output2 改變以下

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

這是因為@ Html.Action實際上不會使用路由。 使用它,您可以明確指定動作和控制器。 例如,當某人從瀏覽器發出http://example.org/Test/Output2請求時,將使用該路由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM