自从升级到RC的WebAPI,我有一些真正奇怪的问题时调用POST在我的WebAPI。
我甚至回到了在新项目上生成的基本版本。所以:
public void Post(string value)
{
}
提琴手喊道:
Header:
User-Agent: Fiddler
Host: localhost:60725
Content-Type: application/json
Content-Length: 29
Body:
{
"value": "test"
}
当我调试时,字符串“value”永远不会被赋值。它总是NULL。
有人有这个问题吗?
(我第一次看到这个问题是在一个更复杂的类型上)
这个问题不仅仅局限于ASP。在asp.net MVC 4中,同样的问题出现在一个新的ASP。NET MVC 3项目后RC安装
不管你想要发布什么类型的值,只要把它括在引号里,就可以得到字符串。不适合复杂类型。
javascript:
var myData = null, url = 'api/' + 'Named/' + 'NamedMethod';
myData = 7;
$http.post(url, "'" + myData + "'")
.then(function (response) { console.log(response.data); });
myData = "some sentence";
$http.post(url, "'" + myData + "'")
.then(function (response) { console.log(response.data); });
myData = { name: 'person name', age: 21 };
$http.post(url, "'" + JSON.stringify(myData) + "'")
.then(function (response) { console.log(response.data); });
$http.post(url, "'" + angular.toJson(myData) + "'")
.then(function (response) { console.log(response.data); });
c#:
public class NamedController : ApiController
{
[HttpPost]
public int NamedMethod([FromBody] string value)
{
return value == null ? 1 : 0;
}
}
尝试创建一个类作为数据模型,然后发送一个具有与数据模型类属性匹配的属性的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; }
}
下面的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" }
我认为必须创建数据模型类的原因是假定简单值来自url参数,而假定单个复杂值来自主体。它们确实有[FromBody]和[FromUrl]属性,但使用[FromBody]字符串值仍然不适合我。看起来他们还在解决很多bug,所以我相信这在未来会改变。
编辑:
让XML在主体中工作。默认的XML序列化器被更改为DataContractSerializer而不是XmlSerializer。在我的全局中放入以下一行。Asax文件修复了这个问题(参考)
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;