Search code examples
asp.net-mvc-routingasp.net-core-webapiasp.net-core-routing

asp.net core web api center routing


I have an issue related with asp.net core center routing. I know we could use Attribute Routing, but I did not find anything related with center routing like asp.net web api.
Something like below:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }

);

Could you share me how to achieve above function in asp.net core? If there is no built-in function, could custom routing service achieve this?
Regards,
Edward


Solution

  • center routing is supported for web api, but we need to disable attribute route on web api.
    Route:

        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 controller:

        //[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";
            }
    }
    

    This could be requested by http://localhost:44888/api/values/getbyid/123