.Net Core 5 Web Api - Swagger POST ok Xunit POST 错误

.Net Core 5 Web Api - Swagger POST ok Xunit POST Error

我正在使用 XUnit 测试我的 WebApi,GET 请求工作正常。但是当通过 XUnit 测试 POST 时,我收到了 404 Bad Request 而 Swagger returns 200 OK

泰斯特

[Theory]
        [InlineData("POST")]
        public async Task ContestCreateTest(string method)
        {
            var _httpClient = new Setup().httpClient;

            var request = new HttpRequestMessage(new HttpMethod(method), "/v1/Contest");

            var contestObject = new
            {
                title = "Concurso automatizado",
                description = "Concurso automatizado",
                submissionDeadLineInit = TimeZoneInfo.ConvertTime(DateTime.UtcNow.AddDays(1), TZConvert.GetTimeZoneInfo("America/Sao_Paulo")).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                submissionDeadLineEnd = TimeZoneInfo.ConvertTime(DateTime.UtcNow.AddDays(2), TZConvert.GetTimeZoneInfo("America/Sao_Paulo")).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                ratingDeadLineInit = TimeZoneInfo.ConvertTime(DateTime.UtcNow.AddDays(3), TZConvert.GetTimeZoneInfo("America/Sao_Paulo")).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                ratingDeadLineEnd = TimeZoneInfo.ConvertTime(DateTime.UtcNow.AddDays(4), TZConvert.GetTimeZoneInfo("America/Sao_Paulo")).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                closingDate = TimeZoneInfo.ConvertTime(DateTime.UtcNow.AddDays(5), TZConvert.GetTimeZoneInfo("America/Sao_Paulo")).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                useDistritoRules = true,
                rules = ""
            };

            string contestJson = JsonConvert.SerializeObject(contestObject);

            request.Content = new StringContent(contestJson, Encoding.UTF8, "multipart/form-data");

            var response = await _httpClient.SendAsync(request);

            response.EnsureSuccessStatusCode();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }

如图所示,您的 API 接受表单,但您发送的数据为 json 格式。

var formDataContent = new MultipartFormDataContent
{
    { new StringContent("Concurso automatizado", Encoding.UTF8), "title"},
    { new StringContent("Concurso automatizado", Encoding.UTF8), "description")},
    { new StringContent(TimeZoneInfo.ConvertTime(DateTime.UtcNow.AddDays(1), TZConvert.GetTimeZoneInfo("America/Sao_Paulo")).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'", Encoding.UTF8), "submissionDeadLineInit" },
    ...
};

// Act
var response = await _client.PostAsync("/v1/Contest", formDataContent);