C# 如何在 HttpWebRequest POST 中将对象作为参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15066156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass an object as a parameter in HttpWebRequest POST?
提问by Rooney
Here I am calling Restful WCF service from my web application and I don't know how to pass an object as parameter in this one. Here is my client code:
在这里,我从我的 Web 应用程序调用 Restful WCF 服务,但我不知道如何在这个应用程序中将对象作为参数传递。这是我的客户端代码:
protected void Button1_Click(object sender, EventArgs e)
{
UserInputParameters stdObj = new UserInputParameters
{
AssociateRefId = "323",
CpecialLoginId = "[email protected]",
PartnerId = "aaaa",
FirstName = "aaaa",
LastName = "bbbb",
Comments = "dsada",
CreatedDate = "2013-02-25 15:25:47.077",
Token = "asdadsadasd"
};
string url = "http://localhost:13384/LinkService.svc/TokenInsertion";
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
System.Net.WebRequest webReq = System.Net.WebRequest.Create(url);
webReq.Method = "POST";
webReq.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(stdObj.GetType());
StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
writer.Close();
webReq.Headers.Add("URL", "http://localhost:13381/IntegrationCheck/Default.aspx");
System.Net.WebResponse webResp = webReq.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string s = sr.ReadToEnd().Trim();
}
catch (Exception ex)
{
}
}
And my service method:
还有我的服务方法:
public string UserdetailInsertion(UserInputParameters userInput)
采纳答案by Knerd
You have to parse the object in the format and write it into the RequestStream.
您必须以格式解析对象并将其写入RequestStream。
Your class
你的班
[Serializable]
class UserInputParameters {
"your properties etc"
};
The code to serialize the object
序列化对象的代码
private void SendData(UserInputParameters stdObj) {
DataContractJsonSerializer ser = new DataContractJsonSerializer(stdObj.GetType());
StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
JavaScriptSerializer jss = new JavaScriptSerializer();
// string yourdata = jss.Deserialize<UserInputParameters>(stdObj);
string yourdata = jss.Serialize(stdObj);
writer.Write(yourdata);
writer.Close();
}
This should be the trick.
这应该是诀窍。
The class JavaScriptSerializer
is located in the namespace System.Web.Script.Serialization
which can be found in the assembly System.Web.Extensions (in System.Web.Extensions.dll)
here is the MSDN Article: http://msdn.microsoft.com/en-us/library/bb337131.aspx
该类JavaScriptSerializer
位于命名空间中System.Web.Script.Serialization
,可以在System.Web.Extensions (in System.Web.Extensions.dll)
此处的程序集中找到MSDN 文章:http: //msdn.microsoft.com/en-us/library/bb337131.aspx
回答by Sheo Dayal Singh
We can not send an Object data to the remote server from server side code using WebRequest class in C# as we can send only stream data to the remote server and object representation in memory is not stream.Hence before sending the object we need to serialize it as a stream and then we are able to send it to the remote server.Below is the complete code.
我们不能使用 C# 中的 WebRequest 类从服务器端代码将对象数据发送到远程服务器,因为我们只能将流数据发送到远程服务器,并且内存中的对象表示不是流。因此在发送对象之前,我们需要对其进行序列化作为一个流,然后我们就可以将它发送到远程服务器。下面是完整的代码。
namespace SendData
{
public class SendObjectData
{
static void Main(string[] args)
{
Employee emp = new Employee();
emp.EmpName = "Raju";
emp.Age = 30;
emp.Profession = "Teacher";
POST(emp);
}
// This method post the object data to the specified URL.
public static void POST(Employee objEmployee)
{
//Serialize the object into stream before sending it to the remote server
MemoryStream memmoryStream = new MemoryStream();
BinaryFormatter binayformator = new BinaryFormatter();
binayformator.Serialize(memmoryStream, objEmployee);
//Cretae a web request where object would be sent
WebRequest objWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
objWebRequest.Method = "POST";
objWebRequest.ContentLength = memmoryStream.Length;
// Create a request stream which holds request data
Stream reqStream = objWebRequest.GetRequestStream();
//Write the memory stream data into stream object before send it.
byte[] buffer = new byte[memmoryStream.Length];
int count = memmoryStream.Read(buffer, 0, buffer.Length);
reqStream.Write(buffer, 0, buffer.Length);
//Send a request and wait for response.
try
{
WebResponse objResponse = objWebRequest.GetResponse();
//Get a stream from the response.
Stream streamdata = objResponse.GetResponseStream();
//read the response using streamreader class as stream is read by reader class.
StreamReader strReader = new StreamReader(streamdata);
string responseData = strReader.ReadToEnd();
}
catch (WebException ex) {
throw ex;
}
}
}
// This is an object that needs to be sent.
[Serializable]
public class Employee
{
public string EmpName { get; set; }
public int Age { get; set; }
public string Profession { get; set; }
}
}