将NameValueCollection发送到http请求C#

Vaj*_*jda 5 c# httpwebrequest

我有这种情况.我们正在使用一些方法进行登录,但是该方法在一些更高的抽象级别上,因此它只有像username和password这样的参数,并且使用这个参数进行一些Name值集合,而不是传递给某个请求构建器.注入此请求构建器以便我可以更改它的实现.现在我们正在使用POST请求,但将来我们可能会使用XML或JSON,因此只需切换注入接口的实现.

问题是,我不能罚款任何库,这将使我的System.Net.HttpWebRequest超出此名称值集合.我需要像这样的原型方法:

WebRequest / HttpWebRequest  CreateRequest(Uri / string, nameValueCollection);
Run Code Online (Sandbox Code Playgroud)

或者,如果没有类似的东西,那么完成所有工作(发送请求,接收响应和解析它们)的库也会很好.但它需要是异步的.

提前致谢.

Ale*_*rey 12

我不是100%确定你想要什么,但是为了创建一个将从NameValueCollection发布一些数据的Web请求,你可以使用这样的东西:

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,您发布的数据取决于您接受的格式.此示例使用查询字符串格式,但如果您切换到JSON或其他东西,您只需要更改处理方式NameValueCollection.

  • 我做了类似的事情,最后发现NameValueCollection将作为字符串转换为html查询字符串.所以不需要做字符串构建器. (2认同)