在webapi中使用POST是很棘手的!
我想在已经正确的答案上再补充一下。
将特别关注POST,因为处理GET是微不足道的。我不认为有很多人会到处寻找通过webapi解决GET问题的方法。不管怎样. .
如果你的问题是-在MVC Web Api中,如何-使用自定义动作方法名而不是通用的HTTP动词?-执行多个帖子?-发布多个简单类型?- Post复杂类型通过jQuery?
那么以下解决方案可能会有所帮助:
首先,要在Web API中使用自定义动作方法,添加一个Web API路由:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}");
}
然后你可以创建动作方法,比如:
[HttpPost]
public string TestMethod([FromBody]string value)
{
return "Hello from http post web api controller: " + value;
}
现在,从浏览器控制台启动下面的jQuery
$.ajax({
type: 'POST',
url: 'http://localhost:33649/api/TestApi/TestMethod',
data: {'':'hello'},
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function(data){ console.log(data) }
});
其次,要执行多个post,这很简单,创建多个动作方法并用[HttpPost]属性装饰。使用[ActionName("MyAction")]来分配自定义名称,等等。将在下面第四点讲到jQuery
Third, First of all, posting multiple SIMPLE types in a single action is not possible.
Moreover, there is a special format to post even a single simple type (apart from passing the parameter in the query string or REST style).
This was the point that had me banging my head with Rest Clients (like Fiddler and Chrome's Advanced REST client extension) and hunting around the web for almost 5 hours when eventually, the following URL proved to be of help. Will quote the relevant content for the link might turn dead!
Content-Type: application/x-www-form-urlencoded
in the request header and add a = before the JSON statement:
={"Name":"Turbo Tina","Email":"na@Turbo.Tina"}
PS:注意到奇怪的语法了吗?
http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api
不管怎样,让我们忘掉那个故事吧。移动:
第四,通过jQuery发布复杂的类型,当然,$.ajax()将立即进入角色:
假设操作方法接受一个Person对象,该对象具有id和名称。因此,从javascript:
var person = { PersonId:1, Name:"James" }
$.ajax({
type: 'POST',
url: 'http://mydomain/api/TestApi/TestMethod',
data: JSON.stringify(person),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data){ console.log(data) }
});
动作看起来像这样:
[HttpPost]
public string TestMethod(Person person)
{
return "Hello from http post web api controller: " + person.Name;
}
以上所有的方法都对我有用!!干杯!