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

问题描述 投票:2回答:2

我可以从我的角度控制器发送一个原始的json对象,在我的web api方法中将其反序列化为已知类型。这很好但我现在需要能够在同一个请求中发送其他参数,这些参数可以是json对象或简单类型,如string或int。

我已经看过像this这样的文章,它们描述了我的问题,但他们是从代码隐藏而不是客户端发送请求。

我试图构造一个json数组并发送它,但我收到以下消息:'无法创建一个抽象类'。

控制器代码(改编)

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对象,如果可以的话。

c# asp.net json angularjs asp.net-web-api
2个回答
5
投票

好的设法通过跟随this article让它工作。

然后我能够在我的api方法签名中使用简单和复杂的类型:

public JsonResult MyAction(StonglyTypedObject myObj, string description)

我传入data参数中的值:

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

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


0
投票
// 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,第二个参数是object,你想要的任何东西都可以在这个对象中传递....

它可能对你有帮助..

© www.soinside.com 2019 - 2024. All rights reserved.