【问题标题】:Posting object/keyvalue with file upload to asp.net core api通过文件上传到 asp.net 核心 api 发布对象/键值
【发布时间】:2020-02-15 12:25:57
【问题描述】:

我一直在尝试将带有附加信息的文件发布到 asp.net core 3+ post api。如果我单独发送这些参数,它会起作用。但是,我想立即发送所需的信息。

我在 ASP.Net Core 3.1 中的模型

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

帖子 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");
            }
        }

从 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;

我收到 415 错误 Unsupported Media Type

问题是如何从 Xamarin 客户端发送所需的参数 或如何将 FileUpload 作为对象的一部分包含在内并将其发送到 接口?

【问题讨论】:

    标签: c# asp.net asp.net-core xamarin.forms asp.net-core-webapi


    【解决方案1】:

    [FromForm]标签装饰你的post方法中的输入参数以绑定到表单。

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

    这是假设您的 PostItem 类与您发布的表单相匹配。添加[FromForm] 至少应该修复415。

    【讨论】:

    • 你太棒了。
    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2020-12-03
    • 2019-07-15
    • 1970-01-01
    • 2018-07-19
    相关资源
    最近更新 更多