使用OWIN SelfHost

时间:2019-05-17 10:01:55

标签: 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").Result;
}

这是基于(我能正常工作的):

Use OWIN to Self-Host 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" />

问题

  

是否找到了无法找到该网址的指针(引发404)?

1 个答案:

答案 0 :(得分:2)

几个小时后,我开始工作了!不出所料,它的含义更深了:

我的控制器给出了此错误:

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

ConfigureAutofacHttpConfiguration的扩展名:

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中的实际基类。