2017-04-03 104 views
2

我需要在c#Web API應用程序中接收json對象以及字節數組。如何在Web API控制器中接收字節數組和json

這是怎麼了發送數據:

public bool SendMedia(string method, Media media) 
{ 
    string filePath = Path.GetFullPath(Path.Combine(filesDirectory, media.FileName)); 
    if (!File.Exists(filePath)) 
    { 
     return false; 
    } 
    using (var client = new HttpClient()) 
    using (var content = new MultipartContent()) 
    { 
     content.Add(new StringContent(JsonConvert.SerializeObject(media), Encoding.UTF8, "application/json")); 
     byte[] b = File.ReadAllBytes(filePath); 
     content.Add(new ByteArrayContent(b, 0, b.Length)); 
     var response = client.PostAsync(new Uri(baseUri, method).ToString(), content).Result; 
     if (response.IsSuccessStatusCode) 
      return true; 
     return false; 
    } 
} 

而且這是我在嘗試接受它:

// POST: api/Media 
[ResponseType(typeof(Media))] 
public HttpResponseMessage PostMedia(Media media, byte[] data) 
{ 
    int i = data.Length; 
    HttpResponseMessage response = new HttpResponseMessage(); 
    if (!ModelState.IsValid) 
    { 
     response.StatusCode = HttpStatusCode.ExpectationFailed; 
     return response; 
    } 

    if (MediaExists(media.MediaId)) 
     WebApplication1Context.db.Media.Remove(WebApplication1Context.db.Media.Where(p => p.MediaId == media.MediaId).ToArray()[0]); 
    WebApplication1Context.db.Media.Add(media); 


    try 
    { 
     WebApplication1Context.db.SaveChanges(); 
    } 
    catch (DbUpdateException) 
    { 
     response.StatusCode = HttpStatusCode.InternalServerError; 
     return response; 
     throw; 
    } 

    response.StatusCode = HttpStatusCode.OK; 
    return response; 
} 

我不知道很多有關在爲Web開發時刻。正在發送一個MultipartContent正確的方法?

回答

3

的框架只能從身體綁定一個項目你想嘗試不工作,所以什麼。

相反,讀取請求的內容,就像你送了它,並提取部分。

[ResponseType(typeof(Media))] 
public async Task<IHttpActionResult> PostMedia() { 

    if (!Request.Content.IsMimeMultipartContent()) { 
     return StatusCode(HttpStatusCode.UnsupportedMediaType); } 

    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync(); 

    var media = await filesReadToProvider.Contents[0].ReadAsAsync<Media>(); 
    var data = await filesReadToProvider.Contents[1].ReadAsByteArrayAsync(); 

    int i = data.Length; 

    if (!ModelState.IsValid) { 
     return StatusCode(HttpStatusCode.ExpectationFailed); 
    } 

    if (MediaExists(media.MediaId)) 
     WebApplication1Context.db.Media.Remove(WebApplication1Context.db.Media.Where(p => p.MediaId == media.MediaId).ToArray()[0]); 
    WebApplication1Context.db.Media.Add(media); 


    try { 
     WebApplication1Context.db.SaveChanges(); 
    } catch (DbUpdateException) { 
     return StatusCode(HttpStatusCode.InternalServerError); 
    } 

    return Ok(media); 
} 

還要注意,在原始代碼幽州的操作有一個[ResponseType(typeof(Media))]但從未返回類型的對象。以上答案包括Ok(media)響應中的模型。

這是一個非常簡單的例子。根據需要添加任何驗證。

+0

謝謝!我會試試看。 – demilp

+0

該方法現在已經接收到該請求,這是一個巨大的改進,但是當它試圖將其作爲MultipartContent投射時,它將保持爲空。 調試說Request.Content是System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent,但是當我嘗試將其轉換爲它,它不會建立,因爲它說,這是無法訪問由於其保護級別。 – demilp

+0

好的,讓我看看。 – Nkosi

相關問題