简体   繁体   English

来自另一个项目的 asp.net webapi selfhost 控制器

[英]asp.net webapi selfhost controllers from another project

I have a webapi2 project and I want to selfhost this api in another project and call the methods with a httpClient .我有一个webapi2项目,我想在另一个项目中自托管这个 api 并使用httpClient调用这些方法。 Here is my code:这是我的代码:

namespace TestSelfHosting.Controllers
{
    public class ProductsController : ApiController
    {
        [HttpGet]
        public string GetProduct()
        {
            return "test";
        }
    }
}

And the code from the test project:以及来自测试项目的代码:

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;
            }
        }
    }
}

But when I'm calling client.GetAsync method, is throwing an error (404, not found).但是当我调用client.GetAsync方法时,抛出错误(404,未找到)。 Is this possible to achieve or am I doing something wrong?这有可能实现还是我做错了什么?

I've followed the tutorial from here我已经按照这里的教程

Have you referenced your webapi2 project in the self-host project (test project)?你有没有在自托管项目(测试项目)中引用你的webapi2项目?

If not, go to your self-host project -> references -> add reference -> locate your webapi2.dll and add it (you must build your webapi2 project beforehand to “generate” the dll file)如果没有,请转到您的自托管项目 -> 引用 -> 添加引用 -> 找到您的 webapi2.dll 并添加它(您必须事先构建您的 webapi2 项目以“生成”dll 文件)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM