Post 从 xamarin 到 restful API

Post from xamarin to restful API

我正在尝试从 xamarin 进行 API 调用,这是我第一个使用 [=38= 调用 restful API (.NetCore3.1) 的完整移动应用程序] 网络应用程序。 来自 xamarin 应用程序的所有其他 API 调用都在工作, 问题是我需要发送一个带有对象的文件,文件可以是 .doc .png 等

GrantApplication.cs API端点

    public class FileProvider
    {
        public string GA { get; set; }
        public IList<IFormFile> Files { get; set; }
    }


         [HttpPost]
        [Route("[action]")]
        public ActionResult SubmitGrantApplication([FromForm] FileProvider fileProvider)
        {
            try
            {
                var ga = fileProvider;
                byte[] fileContent = null;
                var files = Request.Form.Files.Any() ? Request.Form.Files : new FormFileCollection();
                var grant = JsonConvert.DeserializeObject<GrantApplication>(ga.GA);
               ...
            }
        }

GrantService.cs 从移动应用程序拨打电话: 此调用返回 400 响应,但没有明确说明原因。 我想弄清楚为什么,我的邮递员技能不是很好,无法将代码转换为邮递员。

#5 返回错误。
::“对象引用未设置到对象的实例。”

public class GrantService
    {
        public static async Task<GrantApplication> SubmitGrant(GrantApplication ga,string file, string FileName, StreamContent FileData)
        {
                Uri requestUri = new Uri($"{ApiSettings.ApiBaseUrl}/grantapplication/SubmitGrantApplication");
                try
                {
                    var upfilebytes = File.ReadAllBytes(file);
                    //using (HttpClient client = new HttpClient())
                    //{
                    //    //MultipartFormDataContent content = new MultipartFormDataContent();
                    //    //ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
                    //    //StringContent GA = new StringContent(JsonConvert.SerializeObject(ga));
                    //    //content.Add(baContent, "Files", FileName);
                    //    //content.Add(GA, "GA");
                    //    //Console.WriteLine(content);
                    //    //var response = await client.PostAsync(requestUri, content);
                    //    //Console.WriteLine(await response.Content.ReadAsStringAsync());
                    //    //return ga;
                    //}
                    using (var formContent = new MultipartFormDataContent())
                    {
                        formContent.Headers.ContentType.MediaType = "multipart/form-data";
                        // 3. Add the filename C:\... + fileName is the path your file
                        Stream fileStream = File.OpenRead(file);
                        formContent.Add(new StreamContent(fileStream), FileName, FileName);
                        var payload = JsonConvert.SerializeObject(ga);
                        HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
                        formContent.Add(content, "GA");
                        using (var client = new HttpClient())
                        {
                            // Bearer Token header if needed
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

                            try
                            {
                                // 4.. Execute the MultipartPostMethod
                                var message = await client.PostAsync(requestUri, formContent);
                                // 5.a Receive the response
                                var result = await message.Content.ReadAsStringAsync();
                                Console.WriteLine(result);
                            }
                            catch (Exception ex)
                            {
                                // Do what you want if it fails.
                                throw ex;
                            }
                        }
                    }
                    return ga;
                }
                catch(Exception ex)
                {
                     Console.WriteLine(ex);
                    return ga;
                }
           
        }
    }

网络系统 Angular API 通话

public SubmitGrantApplication(grantApplication){
    grantApplication.memberId = JSON.parse(sessionStorage.getItem("LoggedInUser")).memberID;
    grantApplication.ClientID = JSON.parse(sessionStorage.getItem("LoggedInUser")).clientID;
    this.headers = new HttpHeaders({ 'Content-Type' :  'multipart/form-data' });
    this.headers = new HttpHeaders({ 'Accept':  'multipart/form-data'});
    let myFormData: FormData = new FormData();
    myFormData.append("Files", grantApplication.documentContent);
    myFormData.append("GA", JSON.stringify(grantApplication));
    return this.http.post<GrantApplication>(this.url+"SubmitGrantApplication", myFormData , { headers: this.headers }).pipe(
    ).toPromise();
  }
  

招摇

Swagger Doc

有效 Angular API Call 作品 Payload Angular

我尝试复制您的案例并使用相同的代码(删除了未使用的代码)

有效,您可以分享 PostAsync 的整个响应吗? url、响应代码和其他属性可以告诉我们一些事情

    public static async Task<dynamic> SubmitGrant(object ga, string file, string FileName)
    {
        var upfilebytes = File.ReadAllBytes(file);
        using (HttpClient client = new HttpClient())
        {
            Uri requestUri = new Uri($"https://localhost:44341/grantapplication/SubmitGrantApplication");
            MultipartFormDataContent content = new MultipartFormDataContent();
            ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
            StringContent GA = new StringContent(JsonConvert.SerializeObject(ga));
            content.Add(baContent, "Files", FileName);
            content.Add(baContent, "Files", 1 + FileName); /* test 2 files */
            content.Add(GA, "GA");
            Console.WriteLine(content);
            var response = await client.PostAsync(requestUri, content);
            Console.WriteLine(response);
            return ga;
        }
    }

调用方式

await SubmitGrant(new { Test = 123 }, "C:\Temp\MyPicture.jpg", "MyPicture.jpg");

接收数据和文件

此 post 完美运行,邮件功能中存在一个问题,无法附加 API 收到的文件,文件属性设置不同,无法附加来自字节数组... 修复了调用并在 API 中添加了抛出异常, 从不 return BadRequest();在捕获部分。错误 400 将抛出而不是标准错误 500 服务器错误