gpt4 book ai didi

c# - 在 OWIN TestServer 上调用 HTTP PUT

转载 作者:行者123 更新时间:2023-11-30 20:21:15 25 4
gpt4 key购买 nike

我一直在尝试使用 OWIN TestServer 类实现集成测试,除了 PUT 或 DELETE 方法的实现外,一切正常。 POST 方法代码(有效)如下所示:

using (var server = TestServer.Create<Startup>())
{
var response = await server.CreateRequest(uri)
.AddHeader("Authorization", "Bearer " + _token)
.And(
request =>
request.Content =
new ObjectContent(typeof (T), command, new JsonMediaTypeFormatter()))
.PostAsync();

Assert.AreEqual(response.StatusCode, expectedStatusCode);

return await response.Content.ReadAsStringAsync();
}

为了执行 PUT 请求,我尝试了以下两种方法:

using (var server = TestServer.Create<Startup>())
{
var response = await server.CreateRequest(uri)
.AddHeader("Authorization", "Bearer " + _token)
.And(
request =>
request.Content =
new ObjectContent(typeof (T), command, new JsonMediaTypeFormatter()))
.And(request => request.Method = = HttpMethod.Put)
.PostAsync();

Assert.AreEqual(response.StatusCode, expectedStatusCode);

return await response.Content.ReadAsStringAsync();
}

using (var server = TestServer.Create<Startup>())
{
var response = await server.CreateRequest(uri)
.AddHeader("Authorization", "Bearer " + _token)
.And(
request =>
request.Content =
new ObjectContent(typeof (T), command, new JsonMediaTypeFormatter()))
.And(request => request.Method = = HttpMethod.Put)
.SendAsync("PUT");

Assert.AreEqual(response.StatusCode, expectedStatusCode);

return await response.Content.ReadAsStringAsync();
}

SendAsync("PUT") 作为不受支持的方法返回。该参数不是可选的。 PostAsync 方法忽略 HTTPMethod.Put 并仍然尝试 POST 动词。

除了 POST 和 GET 之外,我如何使用这些动词和其他动词?

最佳答案

事实上,我在问了这个问题后几分钟就发现了问题。问题最终成为路线问​​题。通过仔细查看响应,我能够确定“405 - 方法不允许”与调用格式无关,而是我的路由不正确。

对于任何其他浏览者,正确的语法只是SendAsync("PUT").And(request => request.Method = = HttpMethod.Put) 甚至不是必需的...

关于c# - 在 OWIN TestServer 上调用 HTTP PUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34342283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com