c# - 在 HttpWebRequest 中提交请求后无法执行此操作

标签 c# asp.net-core httpwebrequest

我在以下代码中遇到错误。

HttpWebRequest webRequest = WebRequest.Create(URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
response.Cookies = webRequest.CookieContainer.GetCookies(webRequest.RequestUri); //Error here
string responseData = responseReader.ReadToEnd();
responseReader.Close();

Error : System.InvalidOperationException: This operation cannot be performed after the request has been submitted. at System.Net.HttpWebRequest.GetResponse()

上面的代码有什么问题?

最佳答案

HttpWebResponse.Cookies Property应该已经包含与响应关联的 cookie。

您还应该避免多次调用 GetResponse

var cookies = new CookieContainer();

HttpWebRequest webRequest = WebRequest.Create(URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;

var response = (HttpWebResponse)webRequest.GetResponse();

using (var responseReader = new StreamReader(response.GetResponseStream())) {
    var responseCookies = response.Cookies;
    string responseData = responseReader.ReadToEnd();
    //...
}

您可以为后续请求重用 cookie 容器,因为它们将由响应添加

关于c# - 在 HttpWebRequest 中提交请求后无法执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52190522/

相关文章:

c# - Unity 添加组件

c# - 更正串联查询。 C# 和 MySQL

c# - 避免应用程序内存不足异常的最佳方法

c# - HttpWebResponse - 正确处理连接

c# - 如何使用 HttpWebRequest 转义 POST 中的 URL 编码数据

c# - 如何在 ViewModel 中交换属性值?无法通过 ref

C# -IComparable<T> 和 IEquatable<T>

c# - 使用标识将集合添加到 ASP.NET Core 中的用户对象

c# - 如何在 ASP.NET Core 中提供正在写入的文件

c# - 验证 POST 请求的输入?