gpt4 book ai didi

c# - POST 多个集合

转载 作者:可可西里 更新时间:2023-11-01 17:06:11 24 4
gpt4 key购买 nike

我有一个这样的方法(对于这个例子,参数名称故意愚蠢):

[HttpPost]
[Route("rest/myMethod")]
public IHttpActionResult MyMethod(string param1, DateTime param2, DateTime param3, IEnumerable<string> param4, IEnumerable<string> param5 = null)
{
return Ok();
}

但是当我在 Swagger 中测试它时,我得到了这个错误:

{
"message": "An error has occurred.",
"exceptionMessage": "Can't bind multiple parameters ('param4' and 'param5') to the request's content.",
"exceptionType": "System.InvalidOperationException",
"stackTrace": ""
}

只要我删除两个收集参数中的一个,它就可以正常工作。

这是为什么呢?如何在我的 WebApi 中发布多个对象集合?

谢谢。

PS:我不知道这是否是一个有用的情报,但这个 WebApi 将从 AngularJS 客户端调用。

最佳答案

How can I POST multiple collections of objects in my WebApi ?

通过将它们包装在 View 模型中:

public class MyViewModel
{
public string Param1 { get; set; }
public DateTime Param2 { get; set; }
public DateTime Param3 { get; set; }
public IEnumerable<string> Param4 { get; set; }
public IEnumerable<string> Param5 { get; set; }
}

您的 POST 操作将作为参数:

[HttpPost]
[Route("rest/myMethod")]
public IHttpActionResult MyMethod(MyViewModel model)
{
return Ok();
}

现在您可以有以下请求:

POST /rest/myMethod HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 174
Connection: close

{
"Param1": "value of param1",
"Param2": "2017-01-18T07:31:02Z",
"Param3": "2017-01-19T07:31:02Z",
"Param4": [ "foo", "bar" ],
"Param5": [ "baz" ]
}

关于c# - POST 多个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41738757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com