将多个参数传递给WebAPI

时间:2015-08-20 15:25:23

标签: json post asp.net-web-api

我有一个简单的Post方法

[ResponseType(typeof(Conversation))]
[HttpPost]
[Route("foo/bar/Function/")]
public Conversation Function(string title, IEnumerable<Participants> participants)
{
}

我想将一些标题和参与者从我的应用程序传递给服务。

这就是我的尝试:

var createNewConversation = function(title, participants) {
var deferred = $q.defer();
var data = {
    title: title,
    participants: participants
};

$http.post("/foo/bar/Function", data, { headers: { 'Content-Type': "application/json" }, withCredentials: true }).success(function(response) {
        deferred.resolve(response);
    }).error(function(err, status) {
        deferred.reject(err);
    });
    return deferred.promise;
};

但请求永远不会到达服务(也就是说没有达到断点)。

知道我做错了吗?

1 个答案:

答案 0 :(得分:2)

你正在发送身体内的两个参数,而web api无法管理这个,你有两个选择:

<强> 1。在URL中发送标题并参与正文:

[ResponseType(typeof(Conversation))]
[HttpPost]
[Route("foo/bar/Function/{title}")]
public Conversation Function(string title, IEnumerable<Participants> participants)
{...}

// JS

var data = {
    participants: participants
};
$http.post("/foo/bar/Function/title", data, ......

<强> 2。发送全身,改变行动:

[ResponseType(typeof(Conversation))]
    [HttpPost]
    [Route("foo/bar/Function/{title}")]
    public Conversation Function([FromBody] MyClassThatHaveTitleAndParticipants data)
    {...}

MyClassThatHaveTitleAndParticipants类必须具有两个属性,标题和参与者。 // JS

var data = {
    title: title,
    participants: participants
};

$http.post("/foo/bar/Function", data, ...
相关问题