简体   繁体   English

发布带有文件上传到 asp.net core api 的对象/键值

[英]Posting object/keyvalue with file upload to asp.net core api

I have been trying to post a file with additonal information to asp.net core 3+ post api.我一直在尝试将包含附加信息的文件发布到 asp.net core 3+ post api。 If I send these params individually, it works.如果我单独发送这些参数,它会起作用。 However, I want to send the required information at once.但是,我想立即发送所需的信息。

My Model in ASP.Net Core 3.1我在 ASP.Net Core 3.1 中的模型

public class PostItem
{
   public string Title { get; set; }
   public IFormFile File { get; set; }
}

The Post API邮政 API

[HttpPost]
        public async Task<IActionResult> Post(PostItem item)
        {
            try
            {
                if (item == null)
                    return BadRequest();
                await Task.Delay(TimeSpan.FromMilliseconds(100));
                //Do Something here
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message + "Internal server error");
            }
        }

Calling the API from Xamarin client从 Xamarin 客户端调用 API

MultipartFormDataContent content = new MultipartFormDataContent();
var values = new[]
{
    new KeyValuePair<string, string>("Title", postItem.Title)
};
foreach(var keyValue in values)
{
      content.Add(new StringContent(keyValue.Value), keyValue.Key);
}

foreach (string file in imagePaths)
{
    byte[] byteArray = File.ReadAllBytes(file);
    content.Add(new ByteArrayContent(byteArray), "file", Path.GetFileName(file));
}
HttpClient client = new HttpClient();
var response = await client.PostAsync(Path.Combine(ApplicationConstants.apiUrl, "item/"), content);
//read response result as a string async into json var
var responsestr = response.Content.ReadAsStringAsync().Result;

I am getting 415 error Unsupported Media Type我收到 415 错误不支持的媒体类型

The question is how to send the required parameter from Xamarin Client or how to include FileUpload as part of an object and send it to the api?问题是如何从 Xamarin Client 发送所需的参数,或者如何将 FileUpload 作为对象的一部分包含并将其发送到 api?

Decorate the input parameter in your post method with a [FromForm] tag to bind to the form.使用[FromForm]标记装饰 post 方法中的输入参数以绑定到表单。

public async Task<IActionResult> Post([FromForm] PostItem item)
{

}

This is assuming that your PostItem class matches the form you are posting.这是假设您的 PostItem 类与您发布的表单相匹配。 Adding [FromForm] should at least fix the 415.添加[FromForm]至少应该修复 415。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM