我有几个与Web API 1正常工作的集成测试,在我升级到Web API 2(5.0)之后它们无法工作并在调用以下代码时给我空引用:
string uri = Url.Link(HttpRouteConstants.RouteName, new { param1 =
paramValue1, param2 = paramValue2 });
基本上 Url.Link 无法找到路线(至少我认为这是问题)。我认为问题在于 HttpConfiguration &路由正在Web API 2中注册。我们必须更改 WebApiConfig 注册调用
这
WebApiConfig.Register(config)
到
GlobalConfiguration.Configure(WebApiConfig.Register);
现在使用集成测试设置时,我正在使用 HttpConfiguration 实例提供 HttpServer ,我无法调用 GlobalConfiguration.Configure( WebApiConfig.Register); 但我正在使用旧方法并执行以下 WebApiConfig.Register(config),这似乎无法正常工作。仅供参考我的路由配置放在WebApiConfig中。
有没有人知道任何变通办法?
这是我正在使用的堆栈:
更新
这是集成测试代码示例
// Create configuration
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
config.DependencyResolver = new NinjectDependencyResolver(Kernel);
//WebApiConfig.Register(config); Below is the excerpt from WebApiConfig
config.EnableCors((System.Web.Http.Cors.ICorsPolicyProvider)config.DependencyResolver.GetService(typeof(System.Web.Http.Cors.ICorsPolicyProvider)));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: HttpRouteConstants.ApplicationAPIRouteName,
routeTemplate: CoreRouteConstants.DefaultApplicationControllerRoute + "/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: HttpRouteConstants.DefaultAPIRouteName,
routeTemplate: CoreRouteConstants.DefaultControllerRoute + "/{id}",
defaults: new { id = RouteParameter.Optional }
);
HttpServer server = null;
try
{
server = new HttpServer(config);
}
catch (Exception ex)
{
throw ex;
}
string controller = String.Format("{0}{1}/api/MyController/{2}/", HttpServerBaseAddress, param1, param2);
var client = new HttpClient(Server);
using (HttpResponseMessage response = client.DeleteAsync(controller, new CancellationTokenSource().Token).Result)
{
response.IsSuccessStatusCode.Should().BeFalse();
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
//Below is the code from MyController
public virtual async Task<HttpResponseMessage> DeleteAsync([FromUri]object key)
{
HttpResponseMessage response = null;
HttpStatusCode statusCode = HttpStatusCode.OK;
bool result = await Store.DeleteAsync(key);
if (!result)
statusCode = HttpStatusCode.NotFound;
response = Request.CreateResponse<bool>(statusCode, result);
string uri = Url.Link(HttpRouteConstants.ApplicationAPIRouteName, new { param1 = "param1", id = key });
//NOTE: uri is null here as I mentioned
response.Headers.Location = new Uri(uri);
return response;
}
谢谢
答案 0 :(得分:0)
您能分享一下您的集成测试的样子吗?我已经尝试了一个集成测试场景,我可以生成链接,所以我很好奇你的代码是怎样的。在我的场景中,我没有使用过Ninject。
GlobalConfiguration.Configure(WebApiConfig.Register);
确保在完成所有Web API配置后调用HttpConfiguration.EnsureInitialized()
。
因此,如果您在集成测试中调用WebApiConfig.Register
,则可以在完成Web API配置后尝试调用HttpConfiguration.EnsureInitialized()
,看看是否可以解决问题。< / p>