Web API-如何发布包含文件的对象

时间:2019-06-09 09:20:49

标签: asp.net-mvc asp.net-web-api

我想知道是否有人可以提供帮助,关于webapi,我的知识还很少!

  • 我有一个网页(ASP.net MVC),允许用户上传文件(HttpPostedFileBase)
  • 然后我的控制器需要创建一个对象并将该对象(带有文件)发布到外部API(以保存文件)

我遇到的问题是我不确定如何将对象正确发布到api吗?

我在线上有几篇文章,但仍然没有得到它:(

这是我到目前为止所做的:

 public class MediaModel
    {
        [Required]
        public string  AccountId{ get; set; }
        [Required]
        public string EntityId { get; set; }

        public HttpPostedFileBase Image { get; set; }
    }

控制器

[HttpPost]
  [Authorize]
  public async Task<ActionResult> Edit(ViewModels.Client client)
  {

    var media = new MediaModel()
      {
        EntityId = client.Id,
        Image = client.Photo,
        AccountId = client.AccountId
       };

     string apiUrl = "http://localhost:11436/api/Client/Media/Upload";
     using (HttpClient client = new HttpClient())
       {
         client.BaseAddress = new Uri(apiUrl);
         // !!! This section is what i'm having difficulty with !!!
         var jsonMedia = JsonConvert.SerializeObject(media);
         var c = new StringContent(jsonMedia, Encoding.UTF8,"application/json");
         HttpResponseMessage response = await client.PostAsync(apiUrl, c);
            if (response.IsSuccessStatusCode)
            {
             //do more
            }
       }

  }

API

[Route("Upload")]
[HttpPost]
    public async Task<IHttpActionResult> Upload(MediaModel media)
    {
      //Read model(and do stuff)

    }

一个我在做错事的例子将不胜感激。

0 个答案:

没有答案