将嵌入的对象作为多部分表单数据发布

时间:2018-09-25 15:01:27

标签: c# asp.net web

我有一个方法可以将模型作为多部分表单数据发送到服务器,但是我不认为如何发布嵌入式对象,例如:

 // Create a request using a URL that can receive a post.   
WebRequest request = WebRequest.Create ("localhost/shoutbox/index.php");  
// Set the Method property of the request to POST.  
request.Method = "POST";  
// Create POST data and convert it to a byte array.  
string postData = "string.Format("username={0}&password={1}", "username", "password")";  
byte[] byteArray = Encoding.UTF8.GetBytes (postData);  
// Set the ContentType property of the WebRequest.  
request.ContentType = "application/x-www-form-urlencoded";  
// Set the ContentLength property of the WebRequest.  
request.ContentLength = byteArray.Length;  
// Get the request stream.  
Stream dataStream = request.GetRequestStream ();  
// Write the data to the request stream.  
dataStream.Write (byteArray, 0, byteArray.Length);  
// Close the Stream object.  
dataStream.Close ();  
// Get the response.  
WebResponse response = request.GetResponse ();  
// Display the status.  
Console.WriteLine (((HttpWebResponse)response).StatusDescription);  
// Get the stream containing content returned by the server.  
dataStream = response.GetResponseStream ();  
// Open the stream using a StreamReader for easy access.  
StreamReader reader = new StreamReader (dataStream);  
// Read the content.  
string responseFromServer = reader.ReadToEnd ();  
// Display the content.  
Console.WriteLine (responseFromServer);  
// Clean up the streams.  
reader.Close ();  
dataStream.Close ();  
response.Close (); 

我创建这样的多部分数据:

public class Model1
{
   public string Field {get;set;}
}

public class Model2
{
   public Model1 Model {get;set;}
}

那么我是否需要采取某种递归方法来监视字段类型是否为对象,并根据它写入数据?如果是这样,我不知道如何找出它是什么类型。只需写var boundary = CreateFormDataBoundary(); var postData = model.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .ToDictionary(prop => prop.Name, prop => prop.GetValue(model, null)); var request = (HttpWebRequest)WebRequest.Create(url + path); request.Method = "POST"; request.KeepAlive = true; request.ContentType = "multipart/form-data; boundary=" + boundary; var requestStream = request.GetRequestStream(); foreach (var item in postData) { if (item.Value != null) { //if list of strings if (item.Value is IEnumerable<string> fields) { if (fields != null) foreach (var field in fields) WriteMultipartFormData(new KeyValuePair<string, string>(item.Key, field), requestStream, boundary); } else { WriteMultipartFormData(new KeyValuePair<string, string>(item.Key, item.Value?.ToString()), requestStream, boundary); } } } var endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--"); requestStream.Write(endBytes, 0, endBytes.Length); requestStream.Close();

0 个答案:

没有答案