POST 多个对象从 Angular 控制器到 Web API 2

POST multiple objects from Angular controller to Web API 2

我能够从我的 angular 控制器发送原始 json 对象,该对象在我的网络 api 方法中被反序列化为已知类型。这很好,但我现在需要能够在同一个请求中发送其他参数,这些参数可以是 json 对象或简单类型,如字符串或整数。

我看过诸如 this 之类的文章,它们准确地描述了我的问题,但他们是从代码隐藏而不是客户端发送请求的。

我试图构建一个 json 数组并将其发送进去,但我收到以下消息:'Cannot create an abstract class'.

控制器代码(改编)

var request = {
            params:[]
        };

        request.params.push(jsonObjectA);
        request.params.push({"someString" : "ABCDEF"});

        $http({
            method: 'POST',
            url: targetUri,
            data: request
        })

Web API 方法签名

 public JsonResult TestMethod(JArray request)

这种方法听起来明智吗?如果可以的话,我真的想避免为每个请求创建 dto 对象。

// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

在post方法中,第一个参数是url,第二个是对象,你想要什么都可以传入这个对象....

可能对你有帮助..

OK 成功地按照 this article.

使它工作

然后我就可以在我的 api 方法签名中使用简单类型和复杂类型了:

public JsonResult MyAction(StonglyTypedObject myObj, string description)

我正在传递数据参数中的值:

 $http({
            method: 'POST',
            url: targetUri,
            data: {
                myObj: myObj,
                description: "desc here"
            }
        }).success(...

这是我能找到的最干净的解决方案,希望对您也有帮助。