asp.net core web api center routing

流过昼夜 提交于 2019-12-24 07:39:06

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/42294177/asp-net-core-web-api-center-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!