当我使用Windows 服务运行我的网站时,我无法访问 wwwroot 中的静态文件,但是当我使用IIS Express 或 IIS时它可以工作。我使用 Asp.Net Core 2.2 构建该项目。
控制器中的动作没问题,只是无法访问静态文件。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var df = new DefaultFilesOptions();
df.DefaultFileNames.Add("Index.html");
app.UseDefaultFiles(df);
app.UseStaticFiles();
app.UseMvc();
}
}
public class Program
{
public static void Main(string[] args)
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));
if (isService)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
var host = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray()).Build();
host.RunAsService();
}
else
{
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build().Run();
}
}
static int Port = 9099;
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => { options.Listen(IPAddress.Any, Port); })
.UseStartup<Startup>();
}
这是因为您在将应用程序作为 Windows 服务运行时设置了目录。
而不是这样做
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
调整您的 Webhost-Build 定义
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => { options.Listen(IPAddress.Any, Port); })
.UseStartup<Startup>()
.UseContentRoot(AppContext.BaseDirectory); // add this line
然后在Startup
类中添加静态文件选项
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var df = new DefaultFilesOptions();
// these options are not necessary index.html is added by default
df.DefaultFileNames.Add("Index.html");
app.UseDefaultFiles(df);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = env.WebRootFileProvider
});
app.UseMvc();
}
还要确保您index.html
始终复制到输出目录。将此添加到您的 csproj 文件中
<Content Update="wwwroot\index.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
或在visual-studio中右键单击它>属性>复制到输出目录>始终复制
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句