Я пытаюсь разместить свое веб-приложение в сервисной фабрике, но мои страницы не загружаются. Я решил, что это как-то связано с моей инициализацией бритвы. Код ниже показывает мою последовательность инициализации. Действия, предоставленные AddRazorOptions
и Configure<RazorViewEngineOptions>
(), никогда не выполняются. Какой вызов вызовет их?
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace WebClient
{
public class LocalServer : IDisposable
{
private IWebHost webHost;
public void Dispose()
{
this.webHost?.Dispose();
}
public void Open()
{
Open(new WebHostBuilder());
}
private void Open(IWebHostBuilder webHostBuilder)
{
string serverUrl = "http://localhost:4040";
CancellationTokenSource webApiCancellationSource = new CancellationTokenSource();
FabricClient fabricClient = new FabricClient();
var contentRootPath = Directory.GetCurrentDirectory();
// Set to website content path
contentRootPath = contentRootPath + @"..\..\..\..\..\WebApplication\Views";
this.webHost = webHostBuilder
.CaptureStartupErrors(true)
.UseKestrel()
/* */
.UseIISIntegration()
/* */
.ConfigureServices(
services => services
.AddSingleton(fabricClient)
.AddSingleton(webApiCancellationSource))
.UseContentRoot(contentRootPath)
.UseSetting("detailedErrors", " true")
.UseSetting("captureStartupErrors", "true")
.UseStartup<Startup>()
.UseUrls(serverUrl)
.Build();
this.webHost.Run();
}
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
var contentRootPath = env.ContentRootPath;
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(contentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services
.AddMvc()
.AddRazorOptions(options =>
{
/* The following code does not execute */
var previous = options.CompilationCallback;
options.CompilationCallback = context =>
{
previous?.Invoke(context);
var refs = AppDomain.CurrentDomain.GetAssemblies()
.Where(x => !x.IsDynamic)
.Select(x => Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(x.Location))
.ToList();
context.Compilation = context.Compilation.AddReferences(refs);
};
//options.ViewLocationFormats.Clear();
//foreach (var locationFormat in new string[]
//{
// @"Views\{0}.cshtml",
// @"Views\Home\{0}.cshtml",
// @"Views\Shared\{0}.cshtml",
//})
//{
// options.ViewLocationFormats.Add(locationFormat);
//}
});
services.Configure<RazorViewEngineOptions>(options =>
{
/* This code does not execute */
options.ViewLocationFormats.Clear();
foreach (var locationFormat in new string[]
{
@"Views\{0}.cshtml",
@"Views\Home\{0}.cshtml",
@"Views\Shared\{0}.cshtml",
})
{
options.ViewLocationFormats.Add(locationFormat);
}
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var execute = true;
if (env.IsDevelopment())
{
execute = true;
}
if (execute)
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
app.UseExceptionHandler(
errorApp =>
errorApp.Run(
context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "text/plain";
IExceptionHandlerFeature feature = context.Features.Get<IExceptionHandlerFeature>();
if (feature != null)
{
Exception ex = feature.Error;
return context.Response.WriteAsync(ex.Message);
}
return Task.FromResult(true);
}));
var contentPath = env.ContentRootPath;
//contentPath = contentPath + @"..\..\..\..\..\WebApplication";
app.UseDefaultFiles(
new DefaultFilesOptions
{
RequestPath = "/WebApplication",
FileProvider = new PhysicalFileProvider(contentPath),
})
.UseStaticFiles(
new StaticFileOptions
{
RequestPath = "/Home",
FileProvider = new PhysicalFileProvider(contentPath + @"\Home"),
});
var dataTokens = new RouteValueDictionary();
var ns = new[] { "WebApplication.Controllers" };
dataTokens["Namespaces"] = ns;
app.UseMvc(
routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}",
defaults: null,
constraints: null,
dataTokens: dataTokens);
})
.Run(async context =>
{
await context.Response.WriteAsync($"Hello world!{Environment.NewLine}");
await context.Response.WriteAsync(string.Format(@"env.ContentRootPath={0}", env.ContentRootPath));
});
}
}
}