【问题标题】:asp.net webapi selfhost controllers from another project来自另一个项目的 asp.net webapi selfhost 控制器
【发布时间】:2017-12-19 14:55:40
【问题描述】:

我有一个 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的教程进行操作

【问题讨论】:

  • 您是否尝试过调用方法 Get 而不是 GetProduct?
  • 如你所见,如果我使用get动词没有动作,它应该调用方法GetProducts。如果我从邮递员那里调用这个 url,它会返回字符串 test

标签: c# asp.net-web-api2 owin self-host-webapi


【解决方案1】:

你是否在自托管项目(测试项目)中引用了你的webapi2项目?

如果没有,请转到您的自托管项目 -> 参考 -> 添加参考 -> 找到您的 webapi2.dll 并添加它(您必须事先构建您的 webapi2 项目以“生成” dll 文件)

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    相关资源
    最近更新 更多