HttpClient未将发布数据发送到NancyFX端点

时间:2020-09-03 15:45:06

标签: api asp.net-core data-binding httpclient nancy

我正在对使用NancyFX端点的Web API进行一些集成测试。我让xUnit测试为集成测试创建测试服务器

 private readonly TestServer _server;
    private readonly HttpClient _client;

    public EventsModule_Int_Tester()
    {
        //Server setup
        _server = new TestServer(new WebHostBuilder()
      .UseStartup<Startup>());
        _server.AllowSynchronousIO = true;//Needs to be overriden in net core 3.1
        _client = _server.CreateClient();
    }

在一种“测试方法”中,我尝试了以下方法

   [Fact]
    public async Task EventTest()
    {
        // Arrange
        HttpResponseMessage expectedRespone = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        var data = _server.Services.GetService(typeof(GenijalnoContext)) as GenijalnoContext;

        //Get come random data from the DBcontext
        Random r = new Random();
        List<Resident> residents = data.Residents.ToList();
        Resident random_residnet = residents[r.Next(residents.Count)];

        List<Apartment> apartments = data.Apartments.ToList();
        Apartment random_Apartment = apartments[r.Next(apartments.Count)];



        EventModel model = new EventModel()
        {
            ResidentId = random_residnet.Id,
            ApartmentNumber = random_Apartment.Id

        };

        //Doesnt work
        IList<KeyValuePair<string, string>> nameValueCollection = new List<KeyValuePair<string, string>> {
        { new KeyValuePair<string, string>("ResidentId", model.ResidentId.ToString()) },
        { new KeyValuePair<string, string>("ApartmentNumber", model.ApartmentNumber.ToString())}
        };

        var result = await _client.PostAsync("/Events/ResidentEnter", new FormUrlEncodedContent(nameValueCollection));



        //Also Doesnt work 
        string json = JsonConvert.SerializeObject(model, Formatting.Indented);
        var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
        var response = await _client.PostAsync("/Events/ResidentEnter", httpContent);

        //PostAsJsonAsync also doesnt work 

        // Assert
        Assert.Equal(response.StatusCode, expectedRespone.StatusCode);
    }

NancyFX模块确实触发了端点并接收了请求,但没有正文

Img1

我在做什么错?请注意,NancyFX端点将Postman呼叫转换为有效模型没有问题。

NancyFX端点 enter image description here

1 个答案:

答案 0 :(得分:0)

好吧,我修复了它,对于那些好奇的人来说,问题在于NancyFX正文阅读器有时无法正确开始阅读请求正文。那就是流读取位置始终不是0(开始)。

要解决此问题,您需要创建一个CustomBoostrapper,然后重写ApplicationStartup函数,以便您可以设置一个将实体位置设置为0的请求前管道

下面的代码

    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        base.ApplicationStartup(container, pipelines);
        pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
        {
            ctx.Request.Body.Position = 0;
            return null;
        });


    }