在Service Fabric上托管WepAPI

时间:2016-11-12 16:25:29

标签: c# asp.net-web-api microservices azure-service-fabric devops

我们刚刚建立了一个内部部署的MS Service Fabric集群。我有一些WebAPI,我想主持它。我正在寻找有关如何使用我们的标准4.5 WebAPI并在Service Fabric中托管它们的资源,而无需创建Service Fabric项目并进行迁移;这似乎太复杂了。

我查看了一些Service Fabric示例项目,似乎所有项目都与Service Fabric紧密结合。我的目标是让这些应用程序不知道Service Fabric。

非常感谢任何信息链接,谢谢!

3 个答案:

答案 0 :(得分:2)

我们这样做了:

  • 在我们的WebAPI的相同解决方案中创建了服务结构项目。
  • 在ServiceFabricHost项目中,我们创建了HttpListenerService以使用服务结构公开端口,就像对SelfHosted WebApi一样。
  • 配置ServiceFabricHost以打开所需的端点。
  • 添加对WebApi项目的引用
  • 使用WebApi Startup发送IAppBuilder并使用我们的外部(SF)配置配置api,如端口和URL。

秘诀是:当你创建一个自托管的web api时,你通常会创建一个控制台应用程序,比如asp.net docs。使用服务结构,您可以使用类似于ConsoleApplication的ServiceFabricService替换控制台,但在这种情况下将是无状态服务。

在这种情况下,我们为HttpListenerService使用了无状态服务,如果需要StateFull服务,则需要重构Api以使用可靠的集合。

Vaclac的同事,为此创建了一个很好的教程: https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-services-communication-webapi/

答案 1 :(得分:0)

如果它是带有自托管Web服务器的独立Web应用程序(例如,Katana,而不是IIS),那么您只需将其作为Guest Executable运行。

如果它不是自托管的并且需要运行单独的Web服务器(如IIS),那么您可以查看在Container中运行它。

答案 2 :(得分:0)

我遇到了同样的问题,并通过在Startup()类中的HttpConfiguration对象上使用DependencyResolver.GetService()方法来解决它。创建一个新的Service Fabric Stateless / Statefull WebAPI项目。在Startup()类中,添加以下代码:

 public static class Startup
{
    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public static void ConfigureApp(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host.
        HttpConfiguration config = new HttpConfiguration();
        // Allow custom routes in controller attributes.
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { controller = "API", action = "HealthCheck", id = RouteParameter.Optional }
        );
        //inject controllers here
        config.DependencyResolver.GetService(typeof({{YourWebAPIRootNamespace}}.Controllers.APIController));

        appBuilder.UseWebApi(config);
    }
}

这允许您将现有API部署到Service Fabric中,而无需将整个代码库迁移到新项目。不要忘记使用web.config中的所有适用设置更新新项目中的app.config。

此处的完整博客帖子http://thenameisirrelevant.com/hosting-an-existing-webapi-in-service-fabric

相关问题