我想将一个简单的类组合在一起,以从发送到我的应用程序的 HTTP 请求中挑选出 QueryString 变量。变量并不总是以相同的顺序排列,但它们始终存在。我想为我的类中的变量分配请求中相应变量的值,但我不知道该怎么做。
代码片段:
MyHTTPRequest ar = new MyHTTPRequest("GET /submit.php?variableOne=value&variableTwo=someothervalue HTTP/1.1"); // Leaving out the rest for now
class MyHTTPRequest
{
public string variableOne;
public string variableTwo;
public string variableThree;
private string[] properties = { "variableOne", "variableTwo", "variableThree" }; // I know they're not actually properties
public MyHTTPRequest(string request)
{
string[] variablePars = request.Substring(16, request.Length - 24).Split('&'); // variablePars now contains "variableOne=value" & "variableTwo=someothervalue"
foreach (string variablePar in variablePars)
{
if (properties.Contains(variablePar.Split('=')[0])) // variableOne, variableTwo, variableThree
{
// Assign the correct variable the value
<???> = variablePar.Split('=')[1]; // I don't know how to pull this one off. variablePar.Split('=')[0] should contain the name of the variable.
}
}
}
}
有什么意见吗?
我确定已经存在类似的问题,但我不知道用什么标题或标签。
最佳答案
使用 System.Web.HttpUtilityClass.ParseQueryString。它返回一个 NameValueCollection,就像您在 ASP.NET 中使用 Request.QueryString 获得的一样。
// assuming you can parse your string to get your string to this format.
string queryStringText = "variableOne=value&variableTwo=someothervalue";
NameValueCollection queryString =
HttpUtility.ParseQueryString(queryStringText);
string variable1 = queryString["variableOne"];
string variable2 = queryString["variableTwo"];
关于C# 分配一个具有特定名称的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3266677/