C#HttpClient-PutAsync

时间:2019-07-15 14:33:13

标签: c# .net-core httpclient

我有一个后端控制器方法

[Route("{ropeId}/segments")]
[HttpPut]
public async Task<IActionResult> Put([NotNull] [FromBody] IEnumerable<Segment> segments)
{
    Debug.WriteLine("In here!");
}

我可以在Rider中使用便签本来达到这个目的

PUT https://localhost:6001/api/ropes/3/segments
Accept: */*
Cache-Control: no-cache
Content-Type: application/json

[{"SegmentNo":1,"RopeId":3,"LastReceived":"2019-12-28T14:34:35.9799039+01:00","BendDamage":0.018,"Temperature":30.0,"LoadLevel":1},
{"SegmentNo":16,"RopeId":3,"LastReceived":"2019-12-28T14:34:35.9799039+01:00","BendDamage":0.018,"Temperature":30.0,"LoadLevel":1}, {"SegmentNo":50,"RopeId":3,"LastReceived":"2019-12-28T14:34:35.9799039+01:00","BendDamage":0.018,"Temperature":30.0,"LoadLevel":1},
{"SegmentNo":69,"RopeId":3,"LastReceived":"2019-12-28T14:34:35.9799039+01:00","BendDamage":0.018,"Temperature":30.0,"LoadLevel":1},
{"SegmentNo":101,"RopeId":3,"LastReceived":"2019-12-28T14:34:35.9799039+01:00","BendDamage":0.018,"Temperature":30.0,"LoadLevel":1},  {"SegmentNo":106,"RopeId":3,"LastReceived":"2019-12-28T14:34:35.9799039+01:00","BendDamage":0.018,"Temperature":30.0,"LoadLevel":1},
{"SegmentNo":128,"RopeId":3,"LastReceived":"2019-12-28T14:34:35.9799039+01:00","BendDamage":0.018,"Temperature":30.0,"LoadLevel":1}]

细分模型:

public sealed class Segment
{
   public Segment(short segmentNo,
                  byte ropeId,
                  DateTime lastReceived,
                  double bendDamage,
                  double temperature,
                  byte loadLevel)
   {
      SegmentNo = segmentNo;
      RopeId = ropeId;
      LastReceived = lastReceived;
      BendDamage = bendDamage;
      Temperature = temperature;
      LoadLevel = loadLevel;
   }

   public short SegmentNo { get; }
   public byte RopeId { get; }
   public DateTime LastReceived { get; }
   public double BendDamage { get; }
   public double Temperature { get; }
   public byte LoadLevel { get; }
}

我无法通过httpClient PutAsync调用来击中它。

我尝试过:

var httpContent = new StringContent(updatedSegments);
var response = await httpClient.PutAsync(@"https://localhost:6001/api/ropes/3/segments", httpContent);

但是我遇到了SerializeError。

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Route matched with {action = "Put", controller = "Ropes"}. Executing action WEBAPI.Controllers.RopesController.Put (WEBAPI)
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.SerializableError'.

我的PutAsync调用有什么问题?

就像我说的那样,这适用于邮递员/ PUT临时操作。

如果我愿意

var s = await httpContent.ReadAsStringAsync();
s.Print();

我得到了上面的JSON,所以我认为问题是我需要以某种方式在httpContent上设置标头以告诉它它是application / json?

1 个答案:

答案 0 :(得分:1)

您是否尝试在构造方法上为httpContent对象指定内容类型?我使用httpClient调用,并声明了对我有用的类型,如下所示:

var httpContent= new StringContent(updatedSegments.ToString(Newtonsoft.Json.Formatting.None), Encoding.UTF8, "application/json");

让我知道它是否也对您有用