【发布时间】:2019-09-28 04:59:45
【问题描述】:
我正在尝试将字符串列表发送到 web api,这个列表我正在类构造函数中初始化,并且我正在传递给 web api 的同一个类。
当我初始化类时;列表已正确填充,但在将其发送到 web api 后,相同的项目将再次添加到列表中。不知道为什么会这样。
因为我从客户那里接受这些值;如果客户端没有提供值,那么我想将默认值填充到列表中。
下面是我的代码
public class RequestDto
{
public RequestDto()
{
TypeNames = new List<string>();
TypeNames.Add(new string("Type1"));
TypeNames.Add(new string("Type2"));
TypeNames.Add(new string("Type3"));
}
public string CompanyName { get; set; }
public string Version { get; set; }
public List<string> TypeNames { get; set; }
}
然后我将类传递给 web api,如下所示
using (var client = new HttpClient())
{
string url = "some url";
var postTask = client.PostAsJsonAsync(url, objrequestdto);
postTask.Wait();
if (postTask.Result.IsSuccessStatusCode)
{
// Do Something
}
}
下面是我的api,在收到参数后我可以看到项目再次被添加。
[HttpPost]
public IActionResult GetTypeDetails([FromBody] RequestDto requestdto) // Here I am getting duplicate/Repeated Values
{
try
{
// Some logic
}
catch (Exception e)
{
Log.Error("Some Error");
return StatusCode(500, e.Message);
}
}
这就是我在调用 web api 之前填充 RequestDto 类的方式。
编辑 1:
RequestDto objrequestdto = GetConfigurations(configName);
private RequestDto GetConfigurations(string configName)
{
RequestDto requestdto = new RequestDto();
/// Add configurations here.
return requestdto;
}
因此,我在 Web API 中得到重复记录。
对此的任何帮助表示赞赏!
【问题讨论】:
-
如果您发送的对象与您发送的对象相同,这是正常的。
-
这不是在客户端序列化后发生的,它与您创建
objrequestdto的方式有关,提供该代码以及您为什么以同步方式调用 Async 方法跨度> -
@MrinalKamboj 我已经编辑了问题并添加了代码
-
@MrinalKamboj 当我调用 web api 时,它再次调用构造函数
标签: c# asp.net-web-api asp.net-core asp.net-web-api2