How to pass complex object as $http params and receive as a view model in API controller action

邮差的信 提交于 2019-12-11 04:15:32

问题


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

public IHttpActionResult Post(string entityType, 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; }
  }

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)
            }
        });

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)
            }
        });

Or,

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

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?

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.


回答1:


You should be able to do

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

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).



来源:https://stackoverflow.com/questions/54645511/how-to-pass-complex-object-as-http-params-and-receive-as-a-view-model-in-api-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!