我有一个webapi2
项目,我想在另一个项目中自托管此api,并使用httpClient
调用方法。这是我的代码:
namespace TestSelfHosting.Controllers
{
public class ProductsController : ApiController
{
[HttpGet]
public string GetProduct()
{
return "test";
}
}
}
以及测试项目中的代码:
namespace TestSelfHosting.Tests
{
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
namespace TestSelfHosting.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
const string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/products").Result;
var content = response.Content.ReadAsStringAsync().Result;
}
}
}
}
但是当我调用client.GetAsync
方法时,抛出一个错误(404,未找到)。这有可能实现还是我做错了?
我已经阅读了here中的教程
您是否已在自托管项目(测试项目)中引用了webapi2项目?
如果没有,请转到自托管项目->引用->添加引用->找到webapi2.dll并将其添加(您必须预先构建webapi2项目才能“生成” dll文件)