将NameValueCollection发送到http请求C#

将NameValueCollection发送到http请求C#,c#,httpwebrequest,C#,Httpwebrequest,我有这种情况。 我们正在使用一些方法进行登录,但该方法是在更高的抽象级别上,所以它只有用户名和密码等参数,这些参数使用这个参数进行名称值收集,然后传递给某个请求生成器。这个请求生成器被注入,以便我可以更改它的实现。现在我们使用POST请求,但将来我们可能会使用XML或JSON,所以只需切换注入接口的实现 问题是,我无法确定任何将使我System.Net.HttpWebRequest脱离此名称值集合的库。 我需要这样的原型方法: WebRequest / HttpWebRequest Creat

我有这种情况。 我们正在使用一些方法进行登录,但该方法是在更高的抽象级别上,所以它只有用户名和密码等参数,这些参数使用这个参数进行名称值收集,然后传递给某个请求生成器。这个请求生成器被注入,以便我可以更改它的实现。现在我们使用POST请求,但将来我们可能会使用XML或JSON,所以只需切换注入接口的实现

问题是,我无法确定任何将使我System.Net.HttpWebRequest脱离此名称值集合的库。 我需要这样的原型方法:

WebRequest / HttpWebRequest  CreateRequest(Uri / string, nameValueCollection);
HttpWebRequest GetRequest(String url, NameValueCollection nameValueCollection)
{
    // Here we convert the nameValueCollection to POST data.
    // This will only work if nameValueCollection contains some items.
    var parameters = new StringBuilder();

    foreach (string key in nameValueCollection.Keys)
    {
        parameters.AppendFormat("{0}={1}&", 
            HttpUtility.UrlEncode(key), 
            HttpUtility.UrlEncode(nameValueCollection[key]));
    }

    parameters.Length -= 1;

    // Here we create the request and write the POST data to it.
    var request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.Method = "POST";

    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(parameters.ToString());
    }

    return request;
}
或者,如果没有类似的东西,那么完成所有工作(发送请求、接收响应和解析它们)的库也会很好。但它必须是异步的


提前感谢。

我不能100%确定您想要什么,但要创建一个web请求,发布来自NameValueCollection的一些数据,您可以使用以下方法:

WebRequest / HttpWebRequest  CreateRequest(Uri / string, nameValueCollection);
HttpWebRequest GetRequest(String url, NameValueCollection nameValueCollection)
{
    // Here we convert the nameValueCollection to POST data.
    // This will only work if nameValueCollection contains some items.
    var parameters = new StringBuilder();

    foreach (string key in nameValueCollection.Keys)
    {
        parameters.AppendFormat("{0}={1}&", 
            HttpUtility.UrlEncode(key), 
            HttpUtility.UrlEncode(nameValueCollection[key]));
    }

    parameters.Length -= 1;

    // Here we create the request and write the POST data to it.
    var request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.Method = "POST";

    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(parameters.ToString());
    }

    return request;
}

但是,您发布的数据将取决于您接受的格式。本例使用查询字符串格式,但如果切换到JSON或其他格式,则只需更改处理
NameValueCollection

的方式即可,这正是我所需要的:谢谢Alex。我做了类似的事情,最后发现NameValueCollection将作为字符串转换为html查询字符串。因此,无需执行字符串生成器。