gpt4 book ai didi

c# - 在 C# 代码中从客户端调用 HttpPost 方法

转载 作者:太空狗 更新时间:2023-10-29 23:59:49 25 4
gpt4 key购买 nike

我是 MVC 和 C# 的新手,如果这个问题看起来太基础了,我很抱歉。

对于如下所示的 HttpPost Controller ,如何在没有浏览器的情况下直接从用 C# 编写的客户端程序调用此方法(不是从带有提交按钮的浏览器中的 UI 表单)?我正在使用 .NET 4 和 MVC 4。

我确信网上有答案,但目前还没有找到。感谢您的帮助!

[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}

最佳答案

例如在服务器端使用这段代码:

[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}

您可以使用不同的方法:

使用 WebClient:

using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["n"] = "42";
data["s"] = "string value";

var response = wb.UploadValues("http://www.example.org/receiver.aspx", "POST", data);
}

使用HttpRequest:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.org/receiver.aspx");

var postData = "n=42&s=string value";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

使用HttpClient:

using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("n", "42"));
values.Add(new KeyValuePair<string, string>("s", "string value"));

var content = new FormUrlEncodedContent(values);

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

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

使用WebRequest

WebRequest request = WebRequest.Create ("http://www.example.org/receiver.aspx");
request.Method = "POST";
string postData = "n=42&s=string value";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();

//Response
WebResponse response = request.GetResponse ();
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();

参见 msdn

关于c# - 在 C# 代码中从客户端调用 HttpPost 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26990773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com