检查 C# .NET 中是否存在 HttpWebRequest
我在后面的代码中声明了以下内容:
private HttpWebRequest req = null;
private IAsyncResult result = null;
我在后面的代码中有一个按钮单击事件,称为 btnUpload:
req = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}", pageUrl.ToString(), arguments));
req.Method = "GET";
// Start the asynchronous request.
result = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(RespCallback), null);
然后,我在同一页面上有另一个按钮单击事件,在后面的代码中称为 btnSubmit,该事件具有:
if (req == null)
req 始终为 null。如何访问 req 和 result 变量?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您的
Page
对象实例无法跨多个 HTTP 请求存活。此行为是 ASP.NET 中设计的。您应该查看
PageAsyncTask
类。这个博客文章对于学习如何使用它可能有用。This is because your
Page
object instance does not live across multiple HTTP requests. This behavior is by design in ASP.NET.You should look at the
PageAsyncTask
class. This blog post may be useful to learn how to use it.如果您正在执行异步请求,则只能在回调方法
RespCallback
中访问结果。您还需要将原始请求传递到异步调用中以获得响应。举个例子:If you're performing an async request, you'll only have access to the result in the callback method
RespCallback
. You'll also need to pass in the original request into the async call get the response. Take the following example:web(编程)是无状态的(除了一些由 viewstate 维护的人工 webform UI 状态),这意味着如果您在 btnUpload_Click 中实例化对象,它将不会出现在另一个按钮事件中。因此,您要么需要在两个按钮的事件中重新创建对象等,例如 HttpWebRequest,要么将 btnUpload_Click 的结果存储在某处(例如在会话中)并从 btnSubmit_click 访问它。还可以通过 google 查找 ASP.net 页面生命周期。
希望这有帮助
the web (programming) is stateless (apart from some artificial webforms UI state maintainted by viewstate), which means if you instantiate object in btnUpload_Click it won't be there in another button event. So you either need to recreate object etc e.g. HttpWebRequest in both buttons' events or store results of btnUpload_Click somewhere (in Session for instance) and access it from btnSubmit_click. Also google for ASP.net page lifecycle.
Hope this helps