WebApi(四)-Post接口请求失败或接受不到参数(解决方法)

post方式只能接受一个参数而且必须用FromBody特性标识,所以当没有使用FromBody特性标识的时候就会请求失败,如有添加添加了那访问接口时候参数应传对象不能是key:val的格式否则会接收到null.

解决方案:

 接收参数如下设置建一个类接收参数

 ajax请求如下:

代码:

 $(function () {
        $('#btn').click(function () {
            var obj = { Id: '1', Name: 'wyb' };
            var jsonStr = JSON.stringify(obj);
            $.ajax({
                type: "Post",
                url: "http://localhost:6212/api/wyb/test/post",
                data: jsonStr,
                dataType: "json",
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                   alert(result.Data.Name)
                },
                error: function (xhr, type, errorThrown)
                {
                    alert('2')
                }
            });
        });
    });

 

Json.stringify()如果没有引用jquery需要引用json.js或者json2.js

posted @ 2016-03-24 10:58  wuyubing  阅读(6760)  评论(0编辑  收藏  举报