我有以下对自我主持的owin api的呼吁:
const string baseAddress = "http://localhost:9000/";
using (WebApp.Start<ApiSelfHost>(url: baseAddress))
{
var client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/v1/orders/test/status").Result;
}
基于(我得到的工作(:
使用owin到自宿主asp.net web api
响应返回以下内容:
状态代码:404,理性词:'找不到'
但是,如果我运行实际的API并转到:
http://localhost:51823/api/v1/orders/test/status
我得到有效的响应。
该控制器动作具有此签名:
[HttpGet]
[Route("api/v1/orders/{orderReference}/status")]
public IHttpActionResult GetOrderStatus([FromUri]string orderReference)
我尝试将该端口9000
更改为51823
,但这没关系。
我安装了以下OWIN软件包:
<package id="Microsoft.Owin" version="4.0.1" targetFramework="net471" />
<package id="Microsoft.Owin.Host.HttpListener" version="4.0.1" targetFramework="net471" />
<package id="Microsoft.Owin.Hosting" version="4.0.1" targetFramework="net471" />
<package id="Microsoft.Owin.Security" version="3.0.1" targetFramework="net471" />
<package id="Microsoft.Owin.Security.Jwt" version="3.0.1" targetFramework="net471" />
<package id="Microsoft.Owin.Security.OAuth" version="3.0.1" targetFramework="net471" />
<package id="Microsoft.Owin.Testing" version="4.0.1" targetFramework="net471" />
问题
任何指示为什么找不到URL(抛出404(?
几个小时后,我才能使用它!正如预期的那样,这是更深的东西:
我的控制器给出了此错误:
no parameterless constructor defined for this object
尽管设置了IOC类型注册:
source.Register(c => MyDbContextMock.Create())
.AsImplementedInterfaces()
.InstancePerRequest();
我错过了这一行:
source.RegisterApiControllers(typeof(OrderController).Assembly);
完整的启动设置为注入:
public class ApiSelfHost : Startup
{
public override void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
var httpConfiguration = new HttpConfiguration();
var container = httpConfiguration.ConfigureAutofac();
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(httpConfiguration);
app.UseWebApi(httpConfiguration);
}
}
其中ConfigureAutofac
是HttpConfiguration
上的扩展名:
internal static IContainer ConfigureAutofac(this HttpConfiguration source)
{
var container = new ContainerBuilder()
.ConfigureAutofac()
.Build();
source.ConfigureDependencyInjection(container);
return container;
}
也在ContainerBuilder
上:
internal static ContainerBuilder ConfigureAutofac(this ContainerBuilder source)
{
source.RegisterApiControllers(typeof(OrderController).Assembly);
source.Register(c => MyDbContextMock.Create())
.AsImplementedInterfaces()
.InstancePerRequest();
return source;
}
Startup
基类是API的实际理由。