繁体   English   中英

在RestSharp中传递对象

[英]Passing Objects In 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,效果很好,因此它必须在Request端,但我无法弄清楚。

有人有建议吗?

事实证明,Bson ObjectId是元凶-出于某种原因,任何序列化程序都无法处理它。 有一个BsonWriter和BsonReader选项,但是这两个选项本质上都使用Base64编码,这很慢并且使消息膨胀。

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

这完美地工作了,另一方面,缺少对象ID不会对MongoDB造成任何问题。 我只是通过唯一的字符串名称查找对象,并在进行任何更改之前分配ID。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM