MVC网站不接收客户端的字符串

Mit*_*sev 5 c# asp.net-mvc json.net

客户:

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);
}
Run Code Online (Sandbox Code Playgroud)

基本上向控制器中的Index动作发送"1" Client.

这是控制器:

[HttpPost]
public ActionResult Index(string k)
{
  Debug.WriteLine(String.Format("Result: {0};", k));
  return Json(new { data = k}, JsonRequestBehavior.DenyGet);
}
Run Code Online (Sandbox Code Playgroud)

结果Client只是"结果:;".控制器的调试输出也是"Result:;".这意味着数据在客户端和站点之间的某处丢失.但是当我调试时,Visual Studio说有一个请求.

Dam*_*mon 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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

来自MSDN

...将 HTTP Content-Type 标头设置为 application/x-www-form-urlencoded,以通知服务器表单数据已附加到帖子中。

我还没有运行 fiddler 来检查默认发送的标头(如果有),但我怀疑没有标头就无法工作的原因是接收客户端不知道在哪里可以找到传递的查询字符串参数。

来自StackOverflow 上的另一个答案

当收到 POST 请求时,您应该始终期待一个“有效负载”,或者用 HTTP 术语来说:消息正文。消息正文本身非常无用,因为没有标准(据我所知。也许应用程序/八位字节流?)格式。正文格式由 Content-Type 标头定义。当使用带有 method="POST" 的 HTML FORM 元素时,这通常是 application/x-www-form-urlencoded。