如何使用 ASP.NET Core 从查询字符串中读取值? [英] How to read values from the querystring with ASP.NET Core?

查看:24
本文介绍了如何使用 ASP.NET Core 从查询字符串中读取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ASP.NET Core MVC 构建一个 RESTful API,我想使用查询字符串参数来指定对返回集合的资源进行过滤和分页.

I'm building one RESTful API using ASP.NET Core MVC and I want to use querystring parameters to specify filtering and paging on a resource that returns a collection.

在这种情况下,我需要读取查询字符串中传递的值来过滤并选择要返回的结果.

In that case, I need to read the values passed in the querystring to filter and select the results to return.

我已经发现在控制器内部 Get 操作访问 HttpContext.Request.Query 返回一个 IQueryCollection.

I've already found out that inside the controller Get action accessing HttpContext.Request.Query returns one IQueryCollection.

问题是我不知道它是如何用来检索值的.事实上,我认为这样做的方法是使用,例如

The problem is that I don't know how it is used to retrieve the values. In truth, I thought the way to do was by using, for example

string page = HttpContext.Request.Query["page"]

问题在于 HttpContext.Request.Query["page"] 不返回字符串,而是返回一个 StringValues.

The problem is that HttpContext.Request.Query["page"] doesn't return a string, but a StringValues.

无论如何,如何使用 IQueryCollection 来实际读取查询字符串值?

Anyway, how does one use the IQueryCollection to actually read the querystring values?

推荐答案

您可以使用 [FromQuery] 将特定模型绑定到查询字符串:

You can use [FromQuery] to bind a particular model to the querystring:

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

例如

[HttpGet()]
public IActionResult Get([FromQuery(Name = "page")] string page)
{...}

这篇关于如何使用 ASP.NET Core 从查询字符串中读取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆