【问题标题】:Passing multiple parameters to WebAPI将多个参数传递给 WebAPI
【发布时间】:2015-11-14 08:01:12
【问题描述】:

我有一个简单的 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;
};

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

知道我做错了什么吗?

【问题讨论】:

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


    【解决方案1】:

    您在正文中发送两个参数,而 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 必须有两个属性,title 和参与者。 //js

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

    【讨论】:

    • 效果很好!非常感谢:)
    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2016-07-18
    • 2013-01-07
    • 2011-10-10
    相关资源
    最近更新 更多