使用jQuery发布到ASP.Net webapi

nan*_*erd 11 jquery post asp.net-web-api

遇到麻烦:

我做了这个简单的测试,警报会弹出文本"test return simple":

jQuery帖子:

$.post("http://www.localhost/webapi/api/corkboard/test/", jsonData)
            .done(function(data){
                alert(data);
        });
Run Code Online (Sandbox Code Playgroud)

Asp.Net WebAPI:

[HttpPost]
public string test()
{        
    return "test return simple";
}
Run Code Online (Sandbox Code Playgroud)

但是当我通过添加参数来更改WebAPI时:

public string test(string JSONData)
    {
        var jData = Json.Decode(JSONData);
        return "test return: " + jData.Filter;            
    }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

"没有找到与请求URI匹配的HTTP资源' http://www.localhost/webapi/api/corkboard/test/ '

坚持并会感激任何想法...谢谢!

Jon*_*iak 15

将WebApi方法更改为:

public string test([FromBody]string JSONData)
    {
        var jData = Json.Decode(JSONData);
        return "test return: " + jData.Filter;            
    }
Run Code Online (Sandbox Code Playgroud)

和你的JQuery:

$.post('http://www.localhost/webapi/api/corkboard/test/', { '': jsonData })
        .done(function(data){
            alert(data);
    });
Run Code Online (Sandbox Code Playgroud)


小智 6

请尝试以下代码..

$.post("http://www.localhost/webapi/api/corkboard/test/", { value: jsonData })
            .done(function(data){
                alert(data);
        });
Run Code Online (Sandbox Code Playgroud)

或者,您可以查看以下链接..

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

  • Chrome表示该链接还包含恶意软件,所以您知道. (8认同)