C# 如何获取请求查询字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18983790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Request Querystring values?
提问by loyalflow
My api client code sends an authentication token in the querystring like:
我的 api 客户端代码在查询字符串中发送一个身份验证令牌,例如:
www.example.com/api/user/get/123?auth_token=ABC123
I'm using Mvc Web api controller, and I have a filter that checks if the auth_token is valid or not, but I'm not sure how to access the request querystring values.
我正在使用 Mvc Web api 控制器,并且我有一个过滤器来检查 auth_token 是否有效,但我不确定如何访问请求查询字符串值。
This is what I am doing now but it is obviously wrong:
这就是我现在正在做的,但显然是错误的:
The below snippet is inside of my filter that inherits from:
下面的代码片段在我的过滤器中,它继承自:
ActionFilterAttribute
动作过滤器属性
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
if (actionContext.Request.Properties.ContainsKey("auth_token") &&
actionContext.Request.Properties["auth_token"].ToString() == "ABC123")
{
...
}
}
回答by Badri
In the OnActionExecuting
method of a filter, you can access the query string and parse it like this to get the token.
在OnActionExecuting
过滤器的方法中,您可以访问查询字符串并像这样解析它以获取令牌。
var queryString = actionContext.Request.RequestUri.Query;
if(!String.IsNullOrWhiteSpace(queryString))
{
string token = HttpUtility.ParseQueryString(
queryString.Substring(1))["auth_token"];
}
But then, is passing a token in query string a good practice? Probably not, but it is up to you. HTTP header could be a better option since query string can get logged and cached.
但是,在查询字符串中传递令牌是一个好习惯吗?可能不是,但这取决于你。HTTP 标头可能是更好的选择,因为查询字符串可以被记录和缓存。
回答by Sipke Schoorstra
Use the GetQueryNameValuePairs extension method, like so:
使用 GetQueryNameValuePairs 扩展方法,如下所示:
var queryString = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
EDITTo avoid duplicate keys, consider doing a ToLookup
:
编辑为避免重复键,请考虑执行以下操作ToLookup
:
var queryString = actionContext.Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);
Here's a blog post on Lookups: https://www.c-sharpcorner.com/UploadFile/vendettamit/using-lookup-for-duplicate-key-value-pairs-dictionary/
这是关于查找的博客文章:https: //www.c-sharpcorner.com/UploadFile/vendettamit/using-lookup-for-duplicate-key-value-pairs-dictionary/