客户端:
WebClient wc = new WebClient();
try
{
string json = wc.UploadString("http://localhost:50001/Client/Index", "1");
dynamic receivedData = JsonConvert.DeserializeObject(json);
Console.WriteLine("Result: {0};",receivedData.data);
}
catch (Exception e)
{
Console.WriteLine("Oh bother");
Console.WriteLine();
Console.WriteLine(e.Message);
}
基本上向Index
控制器中的Client
操作发送“1”。
这是控制器:
[HttpPost]
public ActionResult Index(string k)
{
Debug.WriteLine(String.Format("Result: {0};", k));
return Json(new { data = k}, JsonRequestBehavior.DenyGet);
}
Client
的结果只是“结果:;”。控制器的调试输出也是“Result:;”。这意味着数据在客户端和站点之间的某处丢失。但是当我调试时,Visual Studio说有一个请求。
答案 0 :(得分:2)
WebAPI可能会将您的参数解释为URI参数。
试试这个:
[HttpPost]
public ActionResult Index([FromBody] string k)
{
Debug.WriteLine(String.Format("Result: {0};", k));
return Json(new { data = k}, JsonRequestBehavior.DenyGet);
}
这告诉WebAPI期望从请求的主体中解除此参数(例如,JSON post payload)
答案 1 :(得分:2)
尝试
string parameters = string.Concat("k=","1");
string url = "http://localhost:50001/Client/Index";
using (Var wc = new WebClient()){
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded;charset=UTF-8";
string result = wc.UploadString(url, parameters);
JObject obj = JObject.Parse(result);
Console.WriteLine("Result: {0};", obj.data);
}`
答案 2 :(得分:2)
通过添加标题并指定参数名称,我设法让它工作(在您的调用方法中):
static void Main(string[] args)
{
WebClient wc = new WebClient();
try
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string json = wc.UploadString("http://localhost:49847/Home/Index", "k=1");
dynamic receivedData = JsonConvert.DeserializeObject(json);
Console.WriteLine("Result: {0};", receivedData.data);
}
catch (Exception e)
{
Console.WriteLine("Oh bother");
Console.WriteLine();
Console.WriteLine(e.Message);
}
}
来自MSDN:
...将HTTP Content-Type标头设置为application / x-www-form-urlencoded, 通知服务器表单数据已附加到帖子。
我没有运行fiddler来检查默认情况下发送了什么(如果有)标头,但我怀疑没有标头这是不行的原因是接收客户端不知道在哪里查找查询字符串参数通过传递。
来自another answer on StackOverflow:
收到POST请求时,您应始终指望“有效负载”, 或者,在HTTP术语中:消息体。消息体本身就是 因为没有标准(据我所知,也许没用) application / octet-stream?)格式。正文格式由 Content-Type标头。使用HTML FORM元素时 method =“POST”,这通常是application / x-www-form-urlencoded。
答案 3 :(得分:1)
您需要稍微更改操作以从请求流中获取已发布的值:
csvdata_d=[]
for i in range(timestep): # timestep = number of files
with open(csvname[i]) as f:
reader = csv.reader(f)
readerlist=list(reader)
for row in readerlist[2:]: # skip two header lines
if len(row) == 0: # empty line definition
break
else:
row=list(row)
csvdata_d.append(row[3]) # fourth column
print(csvdata_d)