asp.net核心Web API无法从客户端发送对象

时间:2018-11-13 13:21:47

标签: c# asp.net-web-api client

这是服务器代码,负责接收来自客户端的请求

[HttpPost("Add")]
        public async Task<IActionResult> Add([FromBody]RequestAdd person)
        {

            if(person != null){
                return Ok("good");
            }

            return Ok("false");
        }

这是客户端发布的代码,我将其添加到多部分json和图像字节中

    public Task<HttpResponseMessage> Uploads(Person person, List<FileInfo> files)
            {


            try
            {
                var jsonToSend = JsonConvert.SerializeObject(person, Formatting.None);
                var multipart = new MultipartFormDataContent();

                var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");
                multipart.Add(body, "JsonDetails");


                foreach (var item in files)
                {
                    var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(item.FullName));

                    multipart.Add(fileContent, item.FullName);
                }


                var client = new HttpClient();
                client.BaseAddress = new Uri(BASE_URL);

                return client.PostAsync("Add", multipart);
            }
            catch
            {
                return null;
            }  
        }

在我有此错误的地方使用此方法的代码

static void Main(string[] args)
                {
                    Method2();
                    Console.ReadLine();
                }

                static void Method2()
                {
                    UploadMultiPart uploadMultiPart = new UploadMultiPart();

                    List<FileInfo> fileInfos = new List<FileInfo>()
                    {
                        new FileInfo(@"C:\asd\full-metal-jacket.png"),
                        new FileInfo(@"C:\asd\full-metal-jacket.png"),
                        new FileInfo(@"C:\asd\full-metal-jacket.png")
                    };

                    Person person = new Person
                    {
                    Name = "Adilbek",
                    SureName = "Ramazanov",
                    Position = "God",
                    Group = "heaven",
                    Phone = 123123
                    };

                var result = loadMultiPart.Uploads(person,fileInfos).Result;
                Console.WriteLine("Status is " + result.StatusCode);
            }

错误代码为Status is UnsupportedMediaType

我不知道如何发送到服务器,请对不起我的英语不好

1 个答案:

答案 0 :(得分:2)

使用[FromForm]属性,而不是[FromBody]属性。

    [HttpPost("Add")]
    public async Task<IActionResult> Add([FromForm]RequestAdd person)
    {

        if(person != null){
            return Ok("good");
        }

        return Ok("false");
    }