【问题标题】:Send and receive a post variable发送和接收 post 变量
【发布时间】:2016-03-11 11:24:37
【问题描述】:

我正在尝试将 post 变量发送到我要重定向到的 url。

我目前正在使用 Get 方法并像这样发送它:

// Redirect to page with url parameter (GET)
Response.Redirect("web pages/livestream.aspx?address="+ ((Hardwarerecorders.Device)devices[arrayIndex]).streamAddress);

然后像这样检索它:

// Get the url parameter here
string address = Request.QueryString["address"];

如何转换我的代码以使用 POST 方法?

B.T.W.,我不想使用表单来发送 post 变量。

【问题讨论】:

标签: c# asp.net post get


【解决方案1】:

使用 HttpClient

发送 POST 查询:

using System.Net.Http;

public string sendPostRequest(string URI, dynamic content)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("http://yourBaseAddress");

        var valuesAsJson = JsonConvert.SerializeObject(content);
        HttpContent contentPost = new StringContent(valuesAsJson, Encoding.UTF8, "application/json");

        var result = client.PostAsync(URI, contentPost).Result;
        return result.Content.ReadAsStringAsync().Result;
    }

client.PostAsync(URI, contentPost)”是内容发送到其他网站的位置。

在另一个网站上,需要建立一个 API 控制器来接收结果,如下所示:

[HttpPost]
    [Route("yourURI")]
    public void receivePost([FromBody]dynamic myObject)
    {
        //..
    }

但是,您可能还想考虑使用 307 重定向,特别是如果这是一个临时解决方案。

https://softwareengineering.stackexchange.com/a/99966

【讨论】:

  • 谢谢!但是我怎么寄呢?而当浏览器到达重定向页面时,我如何检索帖子内容?
  • 我有点误解了,上面的方法只是从一个位置发送并接收结果。现在更新。
  • 安装thisnuget包,然后添加对System.Net.Assembly的引用
  • 我也无法评论 A Biswas 的其他答案,但 Get 和 Post 不能这样工作!您不会从一端发布并从另一端获取它,它们是两个独立的协议! GET 方法仍然发送请求,只是不包含包含内容的主体。
  • 您是否将它安装在解决方案中的正确项目中?链接中描述的方法是引用 HttpClient 的正确方法,所以你一定是做错了什么......
【解决方案2】:
using System.Net.Http;

发布

using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
       { "thing1", "hello" },
       { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();
}

获取

using (var client = new HttpClient())
{
    var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx");
}

我的个人选择是 Restsharp,它速度很快,但对于基本操作,您可以使用它

【讨论】:

  • @A 但有一件事我不明白..如何使用给定的帖子变量重定向到给定的页面并在重定向的页面中检索它们?
  • 只要在你想要获取数据的页面中使用“get”代码,你的数据就会保存在responseString中
  • 它说:“找不到类型或命名空间'HttpClient'”..我尝试导入命名空间'System.Net.Http',但找不到Http。 . 有什么解决办法吗?
  • 添加这个using System.Net.Http;
猜你喜欢
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
相关资源
最近更新 更多