如何在asp.net web api中使用接收POST数据?

Tar*_*Tar 2 jquery c#-4.0 asp.net-mvc-4 asp.net-web-api

我用谷歌搜索了一整天,但仍然找不到答案.我需要POST通过数据jQuery.postWeb API MVC-4却无力.这是我的路线:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

这是我的Controller(GET作品!):

    public string Get(int id)
    {
        return "value";
    }

    public void Post([FromBody]string data)
    {
        //body...
    }
Run Code Online (Sandbox Code Playgroud)

这是 jQuery.post:

$.post('api/mycontroller', { key1: 'val1' });
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?

编辑:

@Darin:我试过这个:

public class UnitDetails{
    public string id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和:

public void Post(UnitDetails id) {
    //body...
}
Run Code Online (Sandbox Code Playgroud)

和:

$.post('api/mycontroller', {id:'string1'});
Run Code Online (Sandbox Code Playgroud)

但我仍然想念一些东西......它并没有停留在Post(...){...}.再次 - Get(...){...}确实有效..?

Dar*_*rov 6

这是设计使用和使用原始类型(如字符串)的唯一方法如下:

$.post('/api/mycontroller', '=' + encodeURIComponent('val1'));
Run Code Online (Sandbox Code Playgroud)

因此POST请求的主体必须包含以下内容:

=val1
Run Code Online (Sandbox Code Playgroud)

代替:

data=val1
Run Code Online (Sandbox Code Playgroud)

这已经在这个帖子中讨论过了.

作为替代方案,您可以定义视图模型:

public class MyViewModel
{
    public string Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后让控制器操作将此视图模型作为参数:

public void Post(MyViewModel model)
{
    //body...
}
Run Code Online (Sandbox Code Playgroud)

与原始类型相反,复杂类型使用格式化程序而不是模型绑定.这里an article介绍了Web API如何进行参数绑定.