首页 > 解决方案 > 在 RestSharp 中传递对象

问题描述

我想我必须在我的 .NET 代码中做一些明显不正确的事情,但我无法弄清楚这个问题。

我有两个应用程序通过 RestSharp 调用进行通信,无论我尝试什么,从一个应用程序到另一个应用程序的 POST 值始终为 NULL。这是我的发送代码:

            var client = new RestClient(_context.CloudUrl + ":" + _context.CloudPort.ToString() + "/api/web/AddRegisteredLocation");
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("cache-control", "no-cache");
            request.AddParameter("application/json", JsonConvert.SerializeObject(myLocation, Formatting.None), ParameterType.RequestBody);

我尝试过 .AddObject、.AddJsonBody、.AddBody - 不使用 NewtonSoft.Json 甚至不传递 XML,但此方法始终接收 NULL 值:

    [Route("AddRegisteredLocation")]
    [HttpPost()]
    public async Task<IActionResult> AddRegisteredLocation([FromBody] string NewStringLocation)
    {
        try
        {
            RegisteredLocation newLocation = JsonConvert.DeserializeObject<RegisteredLocation>(NewStringLocation);
            await _Manager.AddRegisteredLocation(newLocation);

            return new OkObjectResult(true);
        }
        catch (Exception exc)
        {
            eventWriter.WriteEntry("AddRegisteredLocation failed with the exception: " + exc.ToString(), System.Diagnostics.EventLogEntryType.Error);
            return new NotFoundResult();
        }

我也试过这个方法:

    //POST: api/web/AddRegisteredLocation
    [Route("AddRegisteredLocation")]
    [HttpPost()]
    public async Task<IActionResult> AddRegisteredLocation([FromBody] RegisteredLocation NewLocation)
    {
        try
        {
            await _Manager.AddRegisteredLocation(NewLocation);

            return new OkObjectResult(true);
        }
        catch (Exception exc)
        {
            eventWriter.WriteEntry("AddRegisteredLocation failed with the exception: " + exc.ToString(), System.Diagnostics.EventLogEntryType.Error);
            return new NotFoundResult();
        }
    }

而且我已经删除了 [FromBody] 标签 - 没有任何效果。当我遍历代码时,传入的值始终为 Null。

如果我使用 Postman 脚本并通过 POST 请求发送原始 JSON,那效果很好,所以它必须是请求端的东西,但我无法弄清楚。

有人有建议吗?

标签: c#json.netrestsharp

解决方案


事实证明,Bson ObjectId 是罪魁祸首——由于某种原因,没有一个序列化程序可以处理它。有一个 BsonWriter 和 BsonReader 选项,但是这两个选项本质上都使用 Base64 编码,这很慢并且会膨胀消息。

为了快速解决这个问题,我最终编写了一组没有 BsonId 的类,然后编写了一堆手动将数据从基于 MongoDB 的类复制到“序列化友好”类的方法。

这非常有效,另一方面,缺少对象 ID 不会导致 MongoDB 出现任何问题。我只是通过唯一的字符串名称查找对象并在进行任何更改之前分配 ID。

这可能不是最优雅的解决方案,但它确实有效!


推荐阅读