gpt4 book ai didi

c# - 如何将对象作为 POST 参数发送到 ASP.Net Web 请求?

转载 作者:太空宇宙 更新时间:2023-11-03 12:23:07 25 4
gpt4 key购买 nike

我正在尝试使用 POST 方法在 ASP.NET 中以编程方式发出 Web 请求。我也想通过网络请求发送 POST 参数。像这样:

LoginData obj = new LoginData();
obj.OSVersion = deviceInformation.OperatingSystem;
obj.DeviceModel = deviceInformation.FriendlyName;
string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";
HttpWebRequest GETRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
GETRequest.Method = "POST";
GETRequest.ContentType = "application/x-www-form-urlencoded";
GETRequest.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
//GETRequest.Parameters.add(obj);

显然,注释行不起作用。我如何实现这一点?

如何通过将我的对象作为参数发送来获得响应?

提前致谢,赫曼斯。

最佳答案

你需要使用属于HttpWebRequestGetRequestStream()方法

void Main()
{
LoginData obj = new LoginData
{
Username = "foo",
Password = "Bar"
};

byte[] objBytes = Encoding.UTF8.GetBytes(obj.ToString());

// obj.OSVersion = deviceInformation.OperatingSystem;
// obj.DeviceModel = deviceInformation.FriendlyName;
string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
request.ContentLength = objBytes.Length;

using (Stream stream = request.GetRequestStream())
{
stream.Write(objBytes, 0, objBytes.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}

}

public class LoginData
{
public string Username { get; set; }
public string Password { get; set; }
public string OSVersion { get; set; }
public string DeviceModel { get; set; }
public override string ToString()
{
var temp = this.GetType()
.GetProperties()
.Select(p => $"{p.Name}={HttpUtility.UrlEncode(p.GetValue(this).ToString())}");

return string.Join("&", temp);
}
}

关于c# - 如何将对象作为 POST 参数发送到 ASP.Net Web 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46419064/

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