在我升级到 Web API 2 (5.0) 后,我几乎没有与 Web API 1 一起正常工作的集成测试,它们无法正常工作,并且在调用以下代码时给了我空引用:
string uri = Url.Link(HttpRouteConstants.RouteName, new { param1 =
paramValue1, param2 = paramValue2 });
基本上Url.Link找不到路线(至少我认为这是问题所在)。我认为问题在于在 Web API 2 中注册HttpConfiguration和路由的方式。我们不得不更改WebApiConfig注册调用
从
WebApiConfig.Register(config)
至
GlobalConfiguration.Configure(WebApiConfig.Register);
现在,当使用集成测试设置时,我为HttpServer提供了HttpConfiguration实例,我不能调用像GlobalConfiguration.Configure(WebApiConfig.Register);这样的东西。但我正在使用旧方法并执行以下WebApiConfig.Register(config)似乎无法正常工作。仅供参考,我的路由配置放在 WebApiConfig 中。
有谁知道任何解决方法?
这是我正在使用的堆栈:
- VS 2013 (.NET 4.5.1)
- WebAPI 2(基于约定的路由和属性路由)
- xUnit
- 忍者
更新
这是集成测试代码示例
// 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;
}
谢谢