2017-07-03 68 views
0

我有一个WebAPI 2.1服务(ASP.Net MVC 4),接收和图像及相关数据。 我需要从WPF应用程序发送此图像,但我得到404未找到错误。c#发送图像从WPF到WebAPI

服务器端

[HttpPost] 
[Route("api/StoreImage")] 
public string StoreImage(string id, string tr, string image) 
{ 
    // Store image on server... 
    return "OK"; 
} 

客户端

public bool SendData(decimal id, int time, byte[] image) 
{ 
    string url = "http://localhost:12345/api/StoreImage"; 
    var wc = new WebClient(); 
    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 
    var parameters = new NameValueCollection() 
    { 
     { "id", id.ToString() }, 
     { "tr", time.ToString() }, 
     { "image", Convert.ToBase64String(image) } 
    }; 
    var res=wc.UploadValues(url, "POST", parameters); 
    return true; 
} 

的网址存在,我的事情,我需要编码为JSON格式,但我不知道怎么办。

谢谢你的时间!

+1

选中[在C#转换对象JSON(https://stackoverflow.com/questions/11345382/convert-object-to-json-string-in- c-sharp) –

+0

已确定属性路由已启用?我也建议使用模型(DTO)来管理数据 – Nkosi

回答

1

您的案例中的方法参数以QueryString的形式收到。

我建议你把参数列表为一个单一的对象是这样的:

public class PhotoUploadRequest 
{ 
    public string id; 
    public string tr; 
    public string image; 
} 

然后你API中的字符串转换从Base64String这样的缓冲:

var buffer = Convert.FromBase64String(request.image); 

然后将其丢到HttpPostedFileBase

HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer); 

现在你有图像文件。做你想做的。

全部代码在这里:

[HttpPost] 
    [Route("api/StoreImage")] 
    public string StoreImage(PhotoUploadRequest request) 
    { 
     var buffer = Convert.FromBase64String(request.image); 
     HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer); 
     //Do whatever you want with filename and its binaray data. 
     try 
     { 

      if (objFile != null && objFile.ContentLength > 0) 
      { 
       string path = "Set your desired path and file name"; 

       objFile.SaveAs(path); 

       //Don't Forget to save path to DB 
      } 

     } 
     catch (Exception ex) 
     { 
      //HANDLE EXCEPTION 
     } 

     return "OK"; 
    } 
+0

感谢@Ramy,它的工作原理! – Duefectu

+0

不客气^ _ ^! @Duefectu –