2

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can configure the routes as options to MVC middleware. Add the routes to the configure method in your startup class

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseMvc(routes =>
    {
        routes.MapRoute("blog", "api/{*article}",
        defaults: new { controller = "Blog", action = "Article" });
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

}

Note that in ASP.NET, the controller are same for both MVC and API. Its an unified model.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.