在一個Action中倘若想實現多種結果返回或者多種輸入參數
就勢必要能夠支援多種路由模板
可能搭配不同權限身份會有不同路由網址
一個action配置多組路由模板
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCoreApiTest1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
[Route("")] //api/account
[Route("/")] //api/account/
[Route("Users")]//api/account/users
public string Users()
{
return "users data...";
}
}
}
不透過Controller層級的路由模板一律下放給各組action設置路由
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCoreApiTest1.Controllers
{
//[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
[Route("Account")] //api/account
[Route("Account/")] //api/account/
[Route("Account/Users")]//api/account/users
public string Users()
{
return "users data...";
}
[Route("Users/{id}")]
[Route("Users/Get/{id}")]
public string GetUserById(string id)
{
return $"User Id: {id}";
}
}
}
Controller層級跟Action層級都有組合路由情況
已下面情況來講就會共有六種路由模板的組合可以訪問
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCoreApiTest1.Controllers
{
[Route("Account")]
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
[Route("")]
[Route("UserList")]
[Route("GetUsers")]
public string Users()
{
return "users data...";
}
}
}
本篇已同步發表至個人部落格
https://coolmandiary.blogspot.com/2021/09/net-core-web-api11.html