Send Json data and file from web aplication to web api net core in same request

494 Views Asked by At

I try to send serialized model in json and a file to a web api on the same request, but I am not able to achieve it, my code below

Web aplication

        HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest;
        request.Method = Verbo;
        request.ContentType = "application/json; charset=utf-8";

        foreach (var item in Body)
        {
            request.Headers.Add(item.Key, item.Value);
        }


        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string json = JsonConvert.SerializeObject(obj, Formatting.Indented);

            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }


        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        StreamReader reader = new StreamReader(response.GetResponseStream());
        respuesta = reader.ReadToEnd();

Web Api

       [HttpPost]
       [Route("Insert")]
       public async Task<OperationResponse> Insert([FromForm]Brand Model)
        {
        var res = new OperationResponse
        {
            Ok = false,
            Message = string.Empty
        };


        return res;
        }

The binding Model is Null

My Json

     {
     "Name": "Jon Doe",
     "TelephoneNumber":"9999999",
     "Email": "[email protected]",
     "Active": false,
     "File": {
     "PathFile": {
         "ContentDisposition": "form-data; name=\"Brand.FileName\"; filename=\"test.p12\"",
         "ContentType": "application/x-pkcs12",
         "Headers": {
             "Content-Disposition": [
                 "form-data; name=\"Brand.FileName\"; filename=\"test.p12\""
              ],
         "Content-Type": [
         "application/x-pkcs12"
            ]
           },
      "Length": 6712,
      "Name": "Brand.FileName",
      "FileName": "test.p12"
      }
     }

am I missing a step?

Thanks a lot.

2

There are 2 best solutions below

0
Ciel On

Postman enters the method insert, but still does the bind in null, the code estaus is 200.

2
Ryan On

Since your content type is application/json; charset=utf-8, you need to use [FromBody] instead of [FromForm].

[HttpPost]
[Route("Insert")]
public async Task<OperationResponse> Insert([FromBody]Brand Model)