web api支持中心路由,但我們需要禁用web api上的屬性路由。
路線:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "api",
template: "api/{controller=Values}/{action=GetAll}/{id?}");
});
的Web API控制器:
//[Route("api/[controller]")]
//[Authorize]
public class ValuesController : Controller
{
private ApplicationDbContext _db;
public ValuesController(ApplicationDbContext db)
{
_db = db;
}
// GET: api/values
//[HttpGet]
public IEnumerable<string> GetAll()
{
var result = from user in _db.UserInfos
select user.UserName;
return result.ToList();
//return new string[] { "value1", "value2" };
}
// GET api/values/5
//[HttpGet("{id}")]
public string GetById(int id)
{
var result = from user in _db.UserInfos
select user.UserName;
return result.FirstOrDefault();
//return User.Identity.IsAuthenticated.ToString(); //"value";
}
}
這可以通過http://localhost:44888/api/values/getbyid/123
請求