如何将复杂对象作为 $http 参数传递并作为 API 控制器操作中的视图模型接收 [英] How to pass complex object as $http params and receive as a view model in API controller action

查看:44
本文介绍了如何将复杂对象作为 $http 参数传递并作为 API 控制器操作中的视图模型接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 API 端点.控制器动作看起来像这样 -

I have an API endpoint. The controller action looks like this -

public IHttpActionResult Post(string entityType, SomeModel someModel)

这里的SomeModel是一个视图模型,看起来像这样 -

Here SomeModel is a view model, which looks like this -

public class SomeModel
  {
    public long? Id { get; set; }
    public long EntityId { get; set; }
    public string Text { get; set; }
  }

我从 angularjs 端调用这个 API 端点 -

I am calling this API endpoint from angularjs end -

return $http({
            method: 'POST',
            url: ENV.apiEndpoint + 'tags',
            params:{
              // here I want to pass parameters which will automatically map into API's two parameter(one string and the other view model)
            }
        });

我不想改变我的 API 端点.我的问题是如何从angular端传递参数,它会自动映射到API方法的参数中.

I don't want to alter my API endpoint. My question is how I can pass parameter from angular end, which will automatically map into the argument of API method.

我尝试了很多东西 -

I have tried a number of things -

var someModel = {id: 1, text:"something", entityId: 12}
return $http({
            method: 'POST',
            url: ENV.apiEndpoint + 'tags',
            params:{
              entityType: entityType,
              someModel: JSON.stringify(someModel)
            }
        });

或者,

var someModel = {id: 1, text:"something"}
return $http({
            method: 'POST',
            url: ENV.apiEndpoint + 'tags',
            params:{
              entityType: entityType,
              id: 1,
              text: "something",
              entityId: 12
            }
        });

这些似乎都不起作用.这意味着参数没有正确映射到 API 方法的参数中.在这种情况下传递参数的理想方式是什么?

None of these seems to work. Meaning the params is not correctly getting mapped into the argument of API method. What is the ideal way to pass params in this type of scenario?

我不想更改我的 API 方法的参数.我知道我可以使用 [FromBody] 或 [FromURI].但我不想做这些.

I don't want to change my API method's argument. I know I can use [FromBody] or [FromURI]. But I don't want to do those.

推荐答案

你应该可以做到

    $http({
        method: 'POST',
        url: ENV.apiEndpoint + 'tags',
        params:{
          entityType: entityType
        },
        data: someModel
    });

默认情况下,POST 请求中的 web api(和 asp.net mvc)反序列化(引用)来自 http 消息体(data)的对象参数和来自 URL 参数(>参数).

By default web api (and asp.net mvc) in a POST request deserializes (reference) object arguments from http message body (data) and value types and string arguments from URL parameters (params).

这篇关于如何将复杂对象作为 $http 参数传递并作为 API 控制器操作中的视图模型接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆