2017-05-25 78 views
4

我們有一個現有的Web API項目,我們現在想從根目錄爲2個客戶端提供服務(通過不同的子域訪問)。設置Web API執行爲兩個網站提供文件並打通路由功能的正確方法是什麼?從Web API提供文件和路由

我看到兩個主要選項:

  1. 使用紅隼作爲文件服務器。我不知道我將如何配置Kestrel從根(來自不同的子域)爲兩個站點提供服務。它似乎具有最小的配置,並且這似乎並不能擴展到基於子域的2個站點。

    var host = new WebHostBuilder() 
        .UseKestrel() 
        .UseWebRoot("wwwroot") 
        .UseIISIntegration() 
        .UseStartup<Startup>() 
        .Build(); 
    
    host.Run(); 
    

    此外,我目前無法將Kestrel與Web API集成,請參閱StackOverflow question

  2. 從負責root的Web API控制器提供文件。這將讀取URL並返回正確的index.html。從那裏我不確定它將如何爲index.html引用提供其他文件,如js/app.js,css/core.css或assets/*。單獨的控制器可以處理這些,但看起來很脆弱。

哪種方法比較合適?或者還有什麼我沒有考慮完成的?

+3

我不明白的是爲什麼你會喜歡混合ASP.NET核心(用紅隼)和Web API(System.Web)在同一個項目中。他們的架構完全不同(我認爲不兼容)。您可以考慮使用Owin [原生路由功能](https://stackoverflow.com/a/25405782/3670737)並提供類似於[app.UseStaticFiles()]的類似靜態文件(https://msdn.microsoft.com /en-us/library/owin.staticfileextensions.usestaticfiles(v=vs.113).aspx)。 –

+1

我結束了使用OWIN,它很好地滿足了我的需求。結合前面評論中鏈接中的信息直接導致實施解決方案。謝謝@FedericoDipuma! –

回答

1

按@ FedericoDipuma的評論,我結束了使用OWIN具有以下Startup.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Owin; 
using Microsoft.Owin.FileSystems; 
using Microsoft.Owin.StaticFiles; 
using System.IO; 

namespace SealingServer 
{ 
    public class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      app.MapWhen(ctx => ctx.Request.Headers.Get("Host").Equals("subdomain1.site.com"), app2 => 
      { 
       var firstClientRoot = Path.Combine("./firstClient/"); 
       var firstClientFileSystem = new PhysicalFileSystem(firstClientRoot); 

       var fileServerOptions = new FileServerOptions(); 
       fileServerOptions.EnableDefaultFiles = true; 
       fileServerOptions.FileSystem = firstClientFileSystem; 
       fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"home.html"}; 
       fileServerOptions.StaticFileOptions.OnPrepareResponse = staticFileResponseContext => 
       { 
        staticFileResponseContext.OwinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=0" }); 
       }; 

       app2.UseFileServer(fileServerOptions); 
      }); 
      app.MapWhen(ctx => ctx.Request.Headers.Get("Host").Equals("subdomain2.site.com"), app2 => 
      { 
       var secondClientRoot = Path.Combine("./secondClient/"); 
       var secondClientFileSystem = new PhysicalFileSystem(secondClientRoot); 

       var fileServerOptions = new FileServerOptions(); 
       fileServerOptions.EnableDefaultFiles = true; 
       fileServerOptions.FileSystem = secondClientFileSystem; 
       fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] { "home.html" }; 
       fileServerOptions.StaticFileOptions.OnPrepareResponse = staticFileResponseContext => 
       { 
        staticFileResponseContext.OwinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=0" }); 
       }; 

       app2.UseFileServer(fileServerOptions); 
      }); 
     } 
    } 
}