asp.net核心Web API中心路由

编程入门 行业动态 更新时间:2024-10-25 18:33:45
本文介绍了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中心路由

本文发布于:2023-10-29 07:47:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   核心   中心   asp   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!