C# 使用OWIN SelfHost时,对httpclient的调用抛出404响应
我对自托管OWIN API进行了以下调用:C# 使用OWIN SelfHost时,对httpclient的调用抛出404响应,c#,owin,webapi2,C#,Owin,Webapi2,我对自托管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").R
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;
}
我得到了一个有效的答复
该控制器操作具有以下签名:
[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
尽管已经建立了国际奥委会类型的注册:
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中的实际基类。请分享ApiSelfHost
@user1859022的代码:我同时找到了解决方案,请看我的答案。
internal static ContainerBuilder ConfigureAutofac(this ContainerBuilder source)
{
source.RegisterApiControllers(typeof(OrderController).Assembly);
source.Register(c => MyDbContextMock.Create())
.AsImplementedInterfaces()
.InstancePerRequest();
return source;
}