如何在ASP.NET 5的WebApi中读取QueryString中的URI参数
问题根因
你传递的command、arguments、_都属于查询字符串参数,没有定义在路由模板中,而GetRouteData()方法只能读取路由模板中配置的路由参数,因此读到的值始终为null。
解决方案
方案1:原生模型绑定(推荐)
ASP.NET Core自带参数绑定能力,无需手动读取HttpContext,直接在Action方法中声明参数并标注[FromQuery]即可自动匹配查询字符串的值:
[HttpGet("GetAllStudents", Name = "[controller]_GetAllStudents")] public ActionResult GetAllStudents( [FromQuery] string command, [FromQuery] string arguments, [FromQuery(Name = "_")] string timestamp) { // 三个参数已经自动绑定,可直接使用 return Ok(); }
提示:
_不符合C#变量命名规范,所以通过Name属性手动指定要绑定的查询参数名即可。
方案2:手动从查询集合读取
如果需要手动读取参数,直接调用Request.Query集合即可,无需额外注入IHttpContextAccessor,ControllerBase自带HttpContext相关属性:
[HttpGet("GetAllStudents", Name = "[controller]_GetAllStudents")] public ActionResult GetAllStudents() { var command = Request.Query["command"]; var arguments = Request.Query["arguments"]; var lastarg = Request.Query["_"]; return Ok(); }
内容的提问来源于stack exchange,提问作者jolynice
相关产品推荐
相关产品推荐

