Cod*_*ody 5 .net c# asp.net-mvc-4 asp.net-web-api
我在ASP.NET MVC 4 RC Web API中得到了我认为是一个奇怪的绑定问题.我有一个方法来接受来自客户端的帖子请求.问题是,当调用post方法时,没有任何参数是绑定的,我到达了抛出线上的断点并且名称,email都是null.如果我在JavaScript中将请求的类型更改为GET,则使用参数绑定调用下面的Get函数.
为什么参数无法为Post方法绑定,我该如何解决这个问题?
send: function(evt) {
evt.preventDefault();
$.ajax( {
url: '/api/person',
data: this.model.toJSON(),
type: "POST",
dataType: "json",
success: function(data) {
console.log("Success");
},
error: function(data) {
console.log("Error");
}
});
}
Run Code Online (Sandbox Code Playgroud)
以下是控制器操作:
public void Get(string name, string email) {
throw new NotImplementedException();
}
public void Post(string name, string email) {
throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)
笔记:
And*_*tan 13
与MVC(网页)不同,默认情况下,简单参数类型不会从帖子主体绑定,而是从URI绑定.因此,使用您的代码,您需要在查询字符串中传递name和email参数或作为路由参数.
然而,这可以通过创建模型类型(以MVC白话)并将其用于方法参数来轻松解决.实际上,您可以将它用于两者(在您给出的情况下),如果您随后[FromUri]在get方法上使用它:
public class SomeParams {
public string name { get; set; }
public string email { get; set; }
}
//now an alternative way to write the Get method
public MyResult Get([FromUri] SomeParams p){
//members are bound from the query string (more like MVC traditional binding)
//note - as in MVC, SomeParams will need a default constructor for this to work.
}
public PostResult Post(SomeParams p){
//'p' is bound from your JSON (assuming correct format)
//because 'complex' types are deserialized using formatters
//only one object can be read from the body with a formatter in Web API
//as the request body is not buffered; unlike MVC.
}
Run Code Online (Sandbox Code Playgroud)
我已经停留在方法的返回类型中,因为它们需要返回一些东西!
我真的建议阅读Mike Stall的文章,我链接到上面(以及他的许多其他人).
很有可能假设Web API,因为它共享相同的范例甚至MVC的类名,实际上与MVC相同 - 但事实并非如此.我最初想知道为什么会这样(因为我自己在MVC上编写了很多REST服务,并且发现它非常酷,一旦你编写了一些实用程序类和基类增强功能),但是他们已经正确地审视了编写Web API的挑战,我认为可能已经对他们所采用的方法进行了更改.
但是,它确实意味着我们必须采取一些我们现在可能认为理所当然的事情,并为Web API重新学习它们.