我一直在尝试使用OWIN TestServer类实现集成测试,除了PUT或DELETE方法的实现之外,一切都有效.POST方法代码(有效)如下所示:
using (var server = TestServer.Create()) { 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()) { 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()) { 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 - Method Not Allowed"与呼叫格式无关,而是我的路线不正确.
对于其他任何浏览的人来说,正确的语法就是SendAsync("PUT").的.而(请求=> request.Method = = HttpMethod.Put)甚至没有必要...