本文介绍了asp核心Web API中心路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到与 asp核心中心路由有关的问题.我知道我们可以使用属性路由,但是没有找到任何与中心路由相关的东西,例如asp Web api. 如下所示:
I have an issue related with asp core center routing. I know we could use Attribute Routing, but I did not find anything related with center routing like asp web api. Something like below:
routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
您能否分享我如何在asp核心中实现上述功能?如果没有内置功能,自定义路由服务可以实现此功能吗? 问候, 爱德华
Could you share me how to achieve above function in asp core? If there is no built-in function, could custom routing service achieve this? Regards, Edward
推荐答案Web api支持中心路由,但是我们需要在Web api上禁用属性路由. 路线:
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控制器:
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"; } }localhost:44888/api/values/getbyid/123
更多推荐
asp.net核心Web API中心路由
发布评论