如何将结构化数据作为HTTP GET请求的参数包含在内?

时间:2015-06-16 23:07:39

标签: angularjs rest asp.net-web-api2

我想将结构化数据作为参数包含在我的HTTP GET调用中,并认为我已正确设置它,但我的API没有像我预期的那样接收数据。如何设置双方以传达结构化数据?

我的角度应用程序向Web API 2中编写的REST API提出了一个复杂的问题。

控制器方法定义为:

[RoutePrefix("v1/questions")]
public class VersionsController : ApiController
{
    [Route("askComplicated")]
    [HttpGet]
    [ResponseType(typeof(ComplicatedResponseDto))]
    public IHttpActionResult AskComplicatedQuestion(ComplicatedRequestDto complicatedRequest)
    {
        var responseElements = new List<ComplicatedResponseElementDto>();
        foreach (var requestElement in complicatedRequest.Elements)
        {
            responseElements.Add(new ComplicatedResponseElementDto()
            {
                Id = requestElement.Id,
                answer = "it is unknowable!!!"
            });
        }
        return Ok(new ComplicatedResponseDto() { Elements = responseElements.ToArray()});
    }

DTO:

public class ComplicatedRequestDto
{
    public ComplicatedRequestElementDto[] Elements { get; set; }
}

public class ComplicatedRequestElementDto
{
    public int Id { get; set; }
    public string Question { get; set; }
}


public class ComplicatedResponseDto
{
    public ComplicatedResponseElementDto[] Elements { get; set; }
}

public class ComplicatedResponseElementDto
{
    public int Id { get; set; }
    public string Answer { get; set; }

}

我以这种方式将其分解,因为我喜欢简单的请求和简单的响应。我采用了最适合我过去WCF工作的模式(并且理解这可能是我的问题)。

从角度来看,这是我的代码:

    var request = $http({
        method: "get",
        url: "http://localhost:65520/v1/questions/askComplicated",
        data: {
            complicatedRequest : {
                elements: [
                  { id: 2, question: 'what is the meaning of life?' },
                  { id: 3, question: 'why am I here?' },
                  { id: 4, question: 'what stock should I pick?' }
                ]
            }
        }
    });
    return request.then(handleSuccess, handleError);

当我从我的角度应用程序调用REST API时,WEB API 2应用程序会收到它,但是ComplicatedRequestDto为null。如何正确发送数据以使其通过?

2 个答案:

答案 0 :(得分:1)

从Get到Post更新您的API,因为当我们想要传递复杂对象时,它包含更多数据,我们有限制在URL中发送最大字符。 做以下修改:

[RoutePrefix("v1/questions")]
public class VersionsController : ApiController
{
    [Route("askComplicated")]
    [HttpPost]
    [ResponseType(typeof(ComplicatedResponseDto))]
    public IHttpActionResult AskComplicatedQuestion([FromBody]ComplicatedRequestDto complicatedRequest)
    {
        //write ur code here...
    }
}

更新您的js代码,如下所示:

 var request = $http({
        method: "post",
        url: "http://localhost:65520/v1/questions/askComplicated",  
        data: {
            complicatedRequest : {
                elements: [
                  { id: 2, question: 'what is the meaning of life?' },
                  { id: 3, question: 'why am I here?' },
                  { id: 4, question: 'what stock should I pick?' }
                ]
            },
        }
    });
    return request.then(handleSuccess, handleError);

答案 1 :(得分:0)

您应该在方法参数之前添加 [FromUri] anotation,以通知WebAPI您要从应用程序Uri加载此参数,这是您在使用GET http操作时数据的用途数据参数。

所以你的代码应该是这样的

[RoutePrefix("v1/questions")]
public class VersionsController : ApiController
{
    [Route("askComplicated")]
    [HttpGet]
    [ResponseType(typeof(ComplicatedResponseDto))]
    public IHttpActionResult AskComplicatedQuestion([FromUri]ComplicatedRequestDto complicatedRequest)
    {
        var responseElements = new List<ComplicatedResponseElementDto>();
        foreach (var requestElement in complicatedRequest.Elements)
        {
            responseElements.Add(new ComplicatedResponseElementDto()
            {
                Id = requestElement.Id,
                answer = "it is unknowable!!!"
            });
        }
        return Ok(new ComplicatedResponseDto() { Elements = responseElements.ToArray()});
    }

您还必须更正有效负载以匹配类的结构。 corect值应如下所示:

{
  "Elements": [
    {
      "Id": 1,
      "Question": "sample string 2"
    },
    {
      "Id": 1,
      "Question": "sample string 2"
    }
  ]
}

最后提供JavaScript代码示例(我只有jQuery,但Angular的有效负载相同):

$.ajax({url:"/v1/questions/askComplicated",data: {
  "Elements": [
    {
      "Id": 2,
      "Question": "what is the meaning of life?"
    },
    {
      "Id": 3,
      "Question": "why am I here?"
    }
  ]
}})