我有一个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
的教程进行了操作答案 0 :(得分:-1)
您是否在自托管项目(测试项目)中引用了webapi2项目?
如果没有,请转到您的自托管项目->引用->添加引用->找到您的webapi2.dll并将其添加(您必须先构建webapi2项目才能“生成” dll文件)