0

我对使用 httpwebrequest 有点困惑。我试图查看一些文章,但由于我是第一次这样做,所以无法从中获得太多。下面是我正在尝试处理的代码,我有几个问题,

a) ASPX 页面定义了一些控件,并且在代码隐藏中我创建了一些控件。当我使用 POST 执行 httpwebrequest 时,是否需要考虑所有控件及其值?我只需要为其中一个控件执行 POST。我可以只为那个控制做吗?

b) 在“(HttpWebRequest)WebRequest.Create”中应该指定什么 URL?我假设它是向用户显示的同一页面。例如,在下面的示例中,它是 ("http://localhost/MyIdentity/Confirm.aspx?ID=New&Designer=True&Colors=Yes");

c) 还有什么我需要在标记或代码中修改或处理以实现 httpwebrequest 吗?

    private void OnPostInfoClick(object sender, System.EventArgs e)
{
    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData =  ""; //Read from the stored array and print each element from the array loop here. 
    byte[] data = encoding.GetBytes(postData);

    // Prepare web request...
    HttpWebRequest myRequest =
      (HttpWebRequest)WebRequest.Create("http://localhost/MyIdentity/Confirm.aspx?ID=New&Designer=True&Colors=Yes");
    myRequest.Method = "POST";
    myRequest.ContentType = "application/x-www-form-urlencoded";
    myRequest.ContentLength = data.Length;
    Stream newStream = myRequest.GetRequestStream();
    // Send the data.
    newStream.Write(data, 0, data.Length);
    newStream.Close();
}
4

1 回答 1

1

通常只会将它用于服务器到服务器的通信(不一定用于页面到页面的数据传输)。

如果我正确理解了您的帖子和问题,您似乎只是想将 POST 数据发送到 ASP.Net 应用程序中的其他页面。如果是这样,您可以这样做的一种方法是简单地更改PostBackUrl您的提交按钮(表单目标)而不是正常的回发(到同一页面)。

还有其他方法,但这应该是最简单的。

<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="foo.aspx" />

在上面,不是 POST 回自身,而是将 POST 发送到foo.aspx您可以检查/使用/处理 POST 数据的地方。


根据您的评论更新:

您不必为此编写通过 HttpWebRequest 的方式。正常的 ASP.net WebForms 模型会为您完成。

鉴于这个简单的 ASP.net Web 表单页面:

<form id="form1" runat="server">

Coffee preference:
<asp:RadioButtonList ID="CoffeeSelections" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
   <asp:ListItem>Latte</asp:ListItem>
   <asp:ListItem>Americano</asp:ListItem>
   <asp:ListItem>Capuccino</asp:ListItem>
   <asp:ListItem>Espresso</asp:ListItem>
</asp:RadioButtonList>

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

....
</form>

您的内联或后面的代码将如下所示:

protected void Page_Load(object sender, EventArgs e)
{
   //do whatever you want to do on Page_Load
}


protected void Button1_Click(object sender, EventArgs e)
{
   //handle the button event
   string _foo = CoffeeSelections.SelectedValue;
   ...
}
于 2012-06-04T14:55:38.403 回答