2013-12-19 29 views
1

我正在研究asp.net Web API。我正在嘗試保存具有圖像數據或文本數據類型屬性的複雜類的列表。我有兩個班,如何發佈multipart表單數據到asp.net web api動作列表

問題類

public class Question 
{ 
    public int QuestionId { get; set; } 
    public string Text { get; set; } 
    public string Type { get; set; } 
} 

響應等級

public class Response 
{ 
    public int ResponseId { get; set; } 
    public int QuestionId { get; set; } 
    public int UserId { get; set; } 
    public string ResponseText { get; set; } 
} 

下面是如何申請表會是什麼樣子,

-------------------------------------- 
1, Question Text (Label) 
    Response (TextBox Control) 
-------------------------------------- 
2, Question Text (Label) 
    Response (File upload control) 
-------------------------------------- 
3, Question Text (Label) 
    Response (TextArea) 
------------------------------------- 
4, Question Text (Label) 
    Response (Either File upload,Textbox other control) 
------------------------------------- 
     | Submit Answers Button | 
------------------------------------- 

當用戶點擊在提交答案按鈕上,所有頁面數據將被髮布到web api操作。

如果都是簡單的文本框,即簡單的表格數據,然後我發佈的數據(表)到網頁API像JSON是,

[{"QuestionId":1,"UserId":321,"ResponseText":"Hello"},{"QuestionId":2,"UserId":321,"ResponseText":"Great"},{"QuestionId":3,"UserId":321,"ResponseText":"Simple"}] 

的Web API,

public HttpResponseMessage SubmitAnswers(HttpRequestMessage request,List<Response> responses) 
{ 
.... 
.... 
.... 
} 

但在我的情況下,我有多部分形式的數據,我也必須張貼多個表單數據,即每個問題與響應被視爲一個單一的形式,所以我們如何張貼多部分形式的數據列表到asp.net web api動作。請指導我。

+0

爲什麼你使用web API而不是MVC控制器動作,這會更簡單。 – Maess

+0

嗯,我需要通過網絡api爲iPhone應用程序提供後端支持,他們的應用程序有問題表單,並將數據發佈到web api。 –

回答

0

您是否使用MultipartFormDataProvider查看過請求是否具有'formurlencoded'數據+文件的多部分請求?...但如果您的請求與'json'數據+文件類似,則可以使用MultipartMemoryStreamProvider ... if文件是巨大的和內存使用是一個問題,您可以創建一個自定義MultipartStreamProvider ...

0

這是代碼尚未測試,但它應該給你一個想法,讓你開始。

// Create a MultipartFormDataContent object 
var multipartContent = new MultipartFormDataContent(); 

int counter = 0; 
foreach (var question in questions) 
{ 
    // Serialize each "question" item found in "questions" 
    var questionJson = JsonConvert.SerializeObject(question, 
    new JsonSerializerSettings 
    { 
     ContractResolver = new CamelCasePropertyNamesContractResolver() 
    }); 

    // Add each serialized question to the multipart object 
    multipartContent.Add(new StringContent(questionJson, Encoding.UTF8, "application/json"), "question" + counter); 
    counter++; 
} 

// Post a petition with a multipart/form-data body 
var response = new HttpClient() 
    .PostAsync("http://multiformserver.com:53908/api/send", multipartContent) 
    .Result; 

var responseContent = response.Content.ReadAsStringAsync().Result; 

我建議你用Fiddler親自看看請願書和回覆的內容。您可以在Fiddler's Documentation網站上找到更多關於如何使用Fiddler的信息。

相關問題