精選文章

網站搬遷

 Hello all, 許久沒有寫部落格的習慣,未來會持續地在  https://alanzhan.dev/  更新

[ASP.NET Core] 設定路由的方式 Build Routing

被同事問到我要怎麼設定路由!
讓我思考了一下!
在Asp.Net Core要怎麼設定路由(Route)呢?
小弟整理幾種方式設定唷!
方案一,在你的Startup類上撰寫!:
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}"
            );
        });
    }
}

當然你還可以這樣設定:
routes.MapRoute(
    name: "default_route",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" }
);

所以你可以擴充你的路由:
app.UseMvc(routes =>
{
    //New Route
    routes.MapRoute(
        name: "about-route",
        template: "about",
        defaults: new { controller = "Home", action = "About" }
    );
 
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}"
    );
});
原本的路由設定還是存在的,
可以到 /Home/About 訪問「About」頁面。



方案二,使用屬性(Attributes):
[Route("[controller]")]
public class AnalyticsController : Controller
{
    [Route("Dashboard")]
    public IActionResult Index()
    {
        return View();
    }
 
    [Route("[action]")]
    public IActionResult Charts()
    {
        return View();
    }
}
我們可以這樣訪問控制器↓↓↓
/Analytics/Dashboard
/Analytics/Charts



方案三,RESTful 路由:
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable Get()
    {
        return new string[] {"Hello", "World!"};
    }
 
    // POST api/values
    [HttpPost]
    public void PostCreate([FromBody] string value)
    {
    }
}
當然我們可以利用HttpGet, HttpPost, HttpPut, HttpDelete屬性!


方案四,使用約束:
[HttpGet("{id:int}")]
public string GetById(int id)
{
    return "item " + id;
}
上面的「{id:int}」可以改成「{id:int?}」
這樣就會變成,id這個參數可傳可不傳,
/GetById/123 或者 /GetById 都可以呼叫的到喔!
當然我們也可以在Startup作約束
routes.MapRoute(
    name: "getProductById",
    template: "Products/{id:int}",
    defaults: new { controller = "Products", action = "GetById" }
);


以上這幾種方案啦!
如果有錯或是其他方案,
歡迎下翻留言鞭策小弟!

參考來源:
https://stormpath.com/blog/routing-in-asp-net-core

留言

這個網誌中的熱門文章