C# 从Web API提供文件和路由服务
我们有一个现有的Web API项目,我们现在希望从根用户那里为2个客户端提供服务(通过不同的子域访问)。设置Web API以执行为两个网站提供文件和点击路由的功能的正确方法是什么 我看到两个主要的选择:C# 从Web API提供文件和路由服务,c#,asp.net-web-api,kestrel-http-server,fileserver,C#,Asp.net Web Api,Kestrel Http Server,Fileserver,我们有一个现有的Web API项目,我们现在希望从根用户那里为2个客户端提供服务(通过不同的子域访问)。设置Web API以执行为两个网站提供文件和点击路由的功能的正确方法是什么 我看到两个主要的选择: 使用Kestrel作为文件服务器。我不确定如何配置Kestrel以从根目录(来自不同的子域)为两个站点提供服务。它似乎有最低限度的配置公开,这似乎不能扩展到基于子域的2个站点 var host = new WebHostBuilder() .UseKestrel() .UseWebR
var host = new WebHostBuilder()
.UseKestrel()
.UseWebRoot("wwwroot")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
var host=new WebHostBuilder()
.UseKestrel()
.UseWebRoot(“wwwroot”)
.Useii整合()
.UseStartup()
.Build();
host.Run();
此外,我目前在将Kestrel与Web API集成时遇到了问题,请参见此以下哪种方法是合适的?还是有什么我没有考虑过的东西可以达到这个目的?根据@FedericoDipuma的评论,我最终在以下Startup.cs中使用了OWIN:
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);
});
}
}
}
我不明白的是,为什么要在同一个项目中混合使用ASP.NET核心(使用Kestrel)和Web API(System.Web)。他们的架构完全不同(我认为不兼容)。您可以考虑使用OWIN,并使用类似的文件来服务静态文件。我最终使用OWIN,它很好地满足了我的需要。结合前面评论中链接中的信息,直接实现了一个解决方案。谢谢@FedericoDipuma!