【问题标题】:How return a dictionary from WebAPI?如何从 WebAPI 返回字典?
【发布时间】:2019-05-31 10:09:48
【问题描述】:

我有一个 MVC 项目,它从一个视图上传一个或多个文件到服务器, 然后,当我单击提交时,一个 provate Web 服务被召回,我传递了一组文件上传。 上传工作正常,但是从 webapi 表单我有一个我会返回的对象(类 Store)。

我不知道我从 web api 返回“原始”对象是错误的还是读取它的错误。

这是我的模特

    public class Store
    {
        public IDictionary<string, string> dictionaryOfStores = new Dictionary<string, string>();
        public string CodeText { get; set; }
    }

我有我的 web api 方法:

public async Task<ActionResult<Store>> UploadAsync()
        {
            dictStores = new Store();
            foreach (var formFile in form.Files)
                    {

                        dictStores.dictionaryOfStores.Add(formFile.FileName, codefilename);
                        // also CodeText is filled here
                    }
                }
            }

            // return dictionary
            //

            return dictStores;
        }

这是我调用私有网络服务的 mvc 控制器

  public async Task<IActionResult> Upload(List<IFormFile> files)
        {

                    using (var client = new HttpClient())
                    {

                            var model = new FilesViewModel();
                            MultipartFormDataContent multiContent = new MultipartFormDataContent();
                            foreach (var formfile in files)
                            {
                                client.BaseAddress = new Uri(BaseAddress);
                                byte[] data;
                                using (var br = new BinaryReader(formfile.OpenReadStream()))
                                    data = br.ReadBytes((int)formfile.OpenReadStream().Length);
                                ByteArrayContent bytes = new ByteArrayContent(data);

                                multiContent.Add(bytes, "file", formfile.FileName);
                                model.Files.Add(new FileDetails { Name = formfile.GetFilename() });
                            }
                            var result = await client.PostAsync("api/Load/Upload", multiContent); // 
                            // here i have try to read result.Content but doesn't have my data
                            var res = await result.Content.ReadAsStreamAsync();
                            // here i have to put res in my model
                            return View("Summary", model);

                    }

我使用 asp net core 2.2 感谢您的帮助

【问题讨论】:

    标签: c# model-view-controller .net-core asp.net-core-webapi


    【解决方案1】:

    我通过看到答案解决了:How to get object using Httpclient with response Ok in Web Api 我能够读取数据:

    await result.Content.ReadAsAsync<Store>()
    

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 2020-07-16
      • 1970-01-01
      • 2014-06-06
      • 2020-08-06
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多