我有一个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,未找到)。这有可能实现还是我做错了什么?
我已经按照这里的教程