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

查看:471
本文介绍了如何使用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.

我已经发现控制器内部获取操作访问 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?

推荐答案

你可以在 IQueryCollection 上使用ToString方法,如果指定了一个 page 参数,它将返回所需的值:

You could use the ToString method on IQueryCollection which will return the desired value if a single page parameter is specified:

string page = HttpContext.Request.Query["page"].ToString();

如果有多个值,例如?page = 1& page = 2 然后ToString调用的结果将是 1,2

if there are multiple values like ?page=1&page=2 then the result of the ToString call will be 1,2

但是作为@mike -g在他的回答中建议你最好使用模型绑定而不是直接访问 HttpContext.Request.Query 对象。

But as @mike-g suggested in his answer you would better use model binding and not directly accessing the HttpContext.Request.Query object.

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

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