C# 帖子参数始终为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10984040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Post parameter is always null
提问by ianrathbone
Since upgrading to RC for WebAPI I'm having some real odd issue when calling POST on my WebAPI. I've even gone back to the basic version generated on new project. So:
自从为 WebAPI 升级到 RC 后,我在 WebAPI 上调用 POST 时遇到了一些非常奇怪的问题。我什至回到了在新项目上生成的基本版本。所以:
public void Post(string value)
{
}
and calling from Fiddler:
并从 Fiddler 调用:
Header:
User-Agent: Fiddler
Host: localhost:60725
Content-Type: application/json
Content-Length: 29
Body:
{
"value": "test"
}
When I debug, the string "value" is never being assigned to. It's just always NULL. Anyone having this issue?
当我调试时,永远不会分配字符串“value”。它总是NULL。有人有这个问题吗?
(I first saw the issue with a more complex type)
(我第一次看到一个更复杂的类型的问题)
The problem is not only bound to ASP.NET MVC 4, the same problem occurs for a fresh ASP.NET MVC 3 project after RC installation
该问题不仅限于 ASP.NET MVC 4,RC 安装后新的 ASP.NET MVC 3 项目也会出现同样的问题
采纳答案by Jim Harte
Since you have only one parameter, you could try decorating it with the [FromBody]attribute, or change the method to accept a DTO with value as a property, as I suggested here: MVC4 RC WebApi parameter binding
由于您只有一个参数,您可以尝试使用[FromBody]属性装饰它,或者更改方法以接受具有值作为属性的 DTO,正如我在此处建议的那样:MVC4 RC WebApi 参数绑定
UPDATE: The official ASP.NET site was updated today with an excellent explanation: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1
更新:官方 ASP.NET 网站今天更新了一个很好的解释:https: //docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part- 1
In a nutshell, when sending a single simple type in the body, send just the value prefixed with an equal sign (=), e.g. body:
简而言之,当在正文中发送单个简单类型时,只发送以等号 (=) 为前缀的值,例如正文:
=test
=test
回答by Sergey Kudriavtsev
Adding line
添加行
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
to the end of function protected void Application_Start()in Global.asax.cs fixed similar problem for me in ASP.NET MVC3.
到protected void Application_Start()Global.asax.cs 中的函数结束在 ASP.NET MVC3 中为我修复了类似的问题。
回答by Despertar
Try creating a class to serve as the data model, then send a JSON object with properties matching the properties of your data model class. (Note: I have tested this and it works with the newest MVC 4 RC 2012 that I just downloaded today).
尝试创建一个类作为数据模型,然后发送一个 JSON 对象,其属性与您的数据模型类的属性相匹配。(注意:我已经对此进行了测试,它适用于我今天刚刚下载的最新 MVC 4 RC 2012)。
public HttpResponseMessage Post(ValueModel model)
{
return Request.CreateResponse<string>(HttpStatusCode.OK, "Value Recieved: " + model.Value);
}
public class ValueModel
{
public string Value { get; set; }
}
The below JSON object is sent in HTTP-POST body, content-type is application/json
下面的 JSON 对象在 HTTP-POST 正文中发送,内容类型为 application/json
{ "value": "In MVC4 Beta you could map to simple types like string, but testing with RC 2012 I have only been able to map to DataModels and only JSON (application/json) and url-encoded (application/x-www-form-urlencoded body formats have worked. XML is not working for some reason" }
I believe the reason why you have to create a data model class is because simple values are assumed to be from the url parameters, and a single complex value is assumed to be from the body. They do have the [FromBody]and [FromUrl]attributes, but using [FromBody] string valuestill did not work for me. Seems like they are still working out a lot of bugs so I'm sure this will change in the future.
我相信您必须创建数据模型类的原因是因为假设简单值来自 url 参数,而假设单个复杂值来自正文。它们确实具有[FromBody]和[FromUrl]属性,但使用[FromBody] string value仍然对我不起作用。似乎他们仍在解决很多错误,所以我相信这会在未来改变。
Edit:Got XML to work in the body. The default XML serializer was changed to DataContractSerializer instead of XmlSerializer. Putting the following line in my Global.asax file fixed this issue (reference)
编辑:让 XML 在正文中工作。默认 XML 序列化程序已更改为 DataContractSerializer 而不是 XmlSerializer。将以下行放在我的 Global.asax 文件中修复了这个问题(参考)
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
回答by danludwig
I know this is not an answer to this question, but I came across it when searching for a solution to my problem.
我知道这不是这个问题的答案,但我在寻找解决问题的方法时遇到了它。
In my case, the complex type was not being bound but I was not doing a POST, I was doing a GET with querystring parameters. The solution was to add [FromUri] to the arg:
在我的例子中,复杂类型没有被绑定,但我没有在做 POST,我在做一个带有查询字符串参数的 GET。解决方案是将 [FromUri] 添加到 arg:
public class MyController : ApiController
{
public IEnumerable<MyModel> Get([FromUri] MyComplexType input)
{
// input is not null as long as [FromUri] is present in the method arg
}
}
回答by Kirk Broadhurst
I've just had this occur using Fiddler. The problem was that I hadn't specified Content-Type.
我刚刚使用 Fiddler 发生了这种情况。问题是我没有指定Content-Type.
Try including a header for Content-Typein your POST request.
尝试Content-Type在您的 POST 请求中包含一个标头。
Content-Type: application/x-www-form-urlencoded
Alternatively, as per comments below, you may need to include a JSON header
或者,根据下面的评论,您可能需要包含一个 JSON 标头
Content-Type: application/json
回答by byobgyn
I had the same issue and found that when changing the Content Type to "application/json" did not fix the problem. However "application/json; charset=utf-8" worked.
我遇到了同样的问题,发现将内容类型更改为“application/json”并没有解决问题。但是“application/json; charset=utf-8”有效。
回答by Richard Pursehouse
I had a similar issue where the request object for my Web API method was always null. I noticed that since the controller action name was prefixed with "Get", Web API treated this as a HTTP GET rather than a POST. After renaming the controller action, it now works as intended.
我有一个类似的问题,我的 Web API 方法的请求对象始终为空。我注意到由于控制器操作名称以“Get”为前缀,因此 Web API 将其视为 HTTP GET 而不是 POST。重命名控制器操作后,它现在可以按预期工作。
回答by George
I've ran into this problem as well, and this is how I solved my problem
我也遇到了这个问题,这就是我解决我的问题的方法
webapi code:
网络API代码:
public void Post([FromBody] dynamic data)
{
string value = data.value;
/* do stuff */
}
client code:
客户端代码:
$.post( "webapi/address", { value: "some value" } );
回答by Ocean Airdrop
I have been scratching my head over this today.
今天我一直在挠头。
My solution is to change the [FromBody]to a HttpRequestMessage, essentially moving up the HTTP stack.
我的解决方案是将 更改[FromBody]为 a HttpRequestMessage,实质上是向上移动 HTTP 堆栈。
In my case I am sending data across the wire which is zipped json which is then base64'd. All this from an android app.
在我的情况下,我通过压缩json的电线发送数据,然后base64'd。所有这一切都来自一个 android 应用程序。
The original signature of my web endpoint looked like this (using [FromBody]) :
我的 Web 端点的原始签名如下所示(使用[FromBody]):


My fix for this issue was to revert to using a HttpRequestMessagefor the signature of my endpoint.
我对此问题的解决方法是恢复使用 aHttpRequestMessage作为端点的签名。


You can then get access to the post data using this line of code:
然后,您可以使用以下代码行访问帖子数据:


This works and allows you access to the raw untouched post data. You don't have to mess around with fiddler putting an = sign at the beginning of your string or changing the content-type.
这有效并允许您访问原始的未修改的帖子数据。您不必与 fiddler 在字符串开头放置 = 符号或更改内容类型混在一起。
As an aside, I first tried to following one of the answers above which was to change the content type to: "Content-Type: application/x-www-form-urlencoded". For raw data this is bad advice because it strips out + characters.
顺便说一句,我首先尝试按照上面的答案之一将内容类型更改为:“内容类型:应用程序/x-www-form-urlencoded”。对于原始数据,这是一个不好的建议,因为它会去掉 + 字符。
So a base64 string that starts like this: "MQ0AAB+LCAAAAAA" ends up like this "MQ0AAB LCAAAAAA"! Not what you want.
所以一个像这样开头的 base64 字符串:“MQ0AAB+LCAAAAAA”以“MQ0AAB LCAAAAAA”结尾!不是你想要的。
Another benefit of using HttpRequestMessageis that you get access to all the http headers from within your endpoint.
使用的另一个好处HttpRequestMessage是您可以访问端点内的所有 http 标头。
回答by eightx2
I had the same problem in Fiddler. I already had Content-Type: application/json; charset=utf-8or Content-Type: application/jsonin the request header.
我在 Fiddler 中遇到了同样的问题。我已经有Content-Type: application/json; charset=utf-8或Content-Type: application/json在请求标头中。
My request body was also a plain string, and in Fiddler I had written: {'controller':'ctrl'}. This made the string parameter in my POST method be null.
我的请求正文也是一个普通的字符串,在 Fiddler 中我写了:{'controller':'ctrl'}. 这使我的 POST 方法中的字符串参数成为null.
Fix: remember to use quotation marks, thereby indicating a string. That is, I fixed it by writing "{'controller':'ctrl'}". (Note: when writing JSON, either be sure to use apostrophes or escape the quotation marks like this: "{\"controller\":\"ctrl\"}").
修复:记得使用引号,从而表示一个字符串。也就是说,我通过编写"{'controller':'ctrl'}". (注意:在编写 JSON 时,请务必使用撇号或像这样转义引号:)"{\"controller\":\"ctrl\"}"。

