我一直在尝试使用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(&#34; PUT&#34;)作为不受支持的方法返回。该参数不是可选的。 PostAsync 方法会忽略 HTTPMethod.Put 并仍尝试POST动词。
如何使用POST和GET以外的这些和其他动词?
答案 0 :(得分:6)
实际上,我在问这个问题后几分钟就找到了问题。问题最终成为路线问题。通过仔细观察响应,我能够确定&#34; 405 - 方法不允许&#34;与呼叫的格式无关,而是我的路线不正确。
对于其他任何浏览者,正确的语法只是 SendAsync(&#34; PUT&#34;)。 .And(request =&gt; request.Method = = HttpMethod.Put)甚至不是必需的......