从 POST 方法检索数据时出现异常?

Getting exception while retrieving data from POST method?

我在读取 post 数据时遇到异常。 我在这一行收到错误:

HttpContext.Current.Request.Form["UserID"].ToString();

错误是:

System.Collections.Specialized.NameValueCollection.this[string].get returned null.

我在方法中放入了这段代码:

StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();

数据是这样正确输入的:

{
  "UserID": "1000",
  "Password": "ABCD"
}

为什么我没有在这个 HttpContext.Current.Request.Form["UserID"].ToString() 中获得价值?我也试过 Request.QueryString 但没有成功。 我哪里做错了?任何帮助或建议将不胜感激。谢谢!

此请求中没有 Form。要将请求正文解释为表单数据,它必须:

  • 内容类型为 x-www-form-urlencoded
  • 实际格式化为表单编码值,即UserID=foo&Password=bar

JSON内容为JSON,不会被解释为表单数据

Web API 应该已经为您解决了这个问题。给定一个动作方法:

public void Action(Credentials credentials)

其中 Credentials class 看起来像:

public class Credentials 
{
    string UserID { get; set;}
    string Password { get; set; }
}

您无需执行任何其他操作即可让框架将传入的 JSON 数据转换为 Credentials 的实例并将其传递给操作方法。这是自动的,除非你做了一些奇怪的事情,打破了 WebAPI 期望的约定。