简体   繁体   English

无法使用Postasync将表单数据发送到Web API

[英]Unable to send form data to web api using postasync

I am trying to send sourceFile value to web api. 我正在尝试将sourceFile值发送到Web API。 But in API i am receiving is null 但是在API中我收到的是null

var formVars = new Dictionary<string, string>();
formVars.Add("sourceFile", "Helloo");

HttpContent content = new FormUrlEncodedContent(formVars);                   

var result = client.PostAsync("ImageApi/Compare", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
return Content(resultContent);

API code API代码

[HttpPost()]
public ActionResult Compare(string sourceFile)
{
   return Ok(sourceFile);
}

I am using DotNet core 2.0 我正在使用DotNet core 2.0

you need to await the result, do not try to access .Result yourself. 您需要等待结果,请勿尝试自行访问.Result。 The call would not have completed at that point. 那时的通话尚未完成。

you need to use something like this: 您需要使用以下内容:

HttpContent content = new FormUrlEncodedContent(formVars);                   

var result = await client.PostAsync("ImageApi/Compare", content);
result .EnsureSuccessStatusCode();
string responseBody = await result.Content.ReadAsStringAsync();

This is based on your code and hasn't been tested but should set you on the right path to get this working. 这是基于您的代码的,尚未经过测试,但应为您设置正确的路径以使其正常工作。 Don't ever try to do async stuff by accessing .Result. 永远不要尝试通过访问.Result来进行异步处理。

One more thing, you need to use a model as well. 还有一件事,您还需要使用模型。

create a model class, which has all the properties you add in your dictionary. 创建一个模型类,其中包含您在字典中添加的所有属性。

in your case it will be something like : 在您的情况下,它将类似于:

public class MyModel{
     public string sourceFile { get ;set; }
}

your controller becomes: 您的控制器将变为:

[HttpPost()]
public ActionResult Compare([FromBody]MyModel model)
{
   return Ok(model.sourceFile);
}

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

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