简体   繁体   English

在同一请求中将 Json 数据和文件从 Web 应用程序发送到 Web api 网络核心

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

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我尝试在同一个请求中将 json 中的序列化模型和一个文件发送到 web api,但我无法实现它,我的代码如下

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": "test@hotmail.com",
     "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.非常感谢。

postman进入方法insert,但是还是在null做bind,code estaus是200。

Since your content type is application/json; charset=utf-8由于您的内容类型是application/json; charset=utf-8 application/json; charset=utf-8 , you need to use [FromBody] instead of [FromForm] . application/json; charset=utf-8 ,您需要使用[FromBody]而不是[FromForm]

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

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

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