angular - 使用单页应用程序 (Spa) 预呈现未通过 IIS AspNetCoreModule 返回正确的 URL 路径
问题描述
我已经设法使用 .NET Core Prerendering 设置了一个单页应用程序 Angular 项目,并且可以确认 Angular 应用程序在服务器端和客户端都可以工作。
我正在使用在生产模式下构建的 AspNetCoreModule 处理程序在 IIS 10 中运行应用程序。同样,我可以确认这是有效的。
每次重新加载页面时,我对 SpaPrendering 上下文中返回的内容有疑问,尤其是相对路径。它总是返回 /index.html,而不是浏览器中的相对路径。
我已经在 Visual Studio 的 IIS Express 中尝试过这个,并且相对路径返回了正确的结果。所以它似乎与 IIS 隔离并使用 AspNetCoreModule 处理程序。
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseKestrel(options =>
{
options.Listen(IPAddress.Loopback, 5443); //HTTP port
})
.UseStartup<Startup>();
}
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_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist/ClientApp";
});
services.AddDbContext<DevResourceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevResourceDbContext")));
services.AddScoped<ImageService>();
services.AddScoped<EnquiryService>();
services.AddScoped<CategoryService>();
services.AddSingleton<RouteBackgroundService>();
// Mapping
services.AddAutoMapper();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
try
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//app.UseExceptionHandler("/Error");
//app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRewriter(new RewriteOptions().AddRedirect("index.html", "/"));
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
spa.UseSpaPrerendering(options =>
{
// If not working, make sure that npm install and npm install @angular-devkit/build-webpack have been ran.
options.BootModulePath = $"ClientApp/dist-server/ClientApp/main.js";
options.BootModuleBuilder = env.IsDevelopment()
? new AngularCliBuilder(npmScript: "build:ssr")
: null;
options.ExcludeUrls = new[] { "/sockjs-node" };
options.SupplyData = (context, data) =>
{
var routeBackgroundService = context.RequestServices.GetRequiredService<RouteBackgroundService>();
data["routes"] = JsonConvert.SerializeObject(new { Paths = routeBackgroundService.GetRouteData() }, Formatting.Indented);
// context.Request.Path always returns index.html, even if
GetSupplyData(context, new Uri(string.Format("{0}://{1}{2}{3}", context.Request.Scheme, context.Request.Host, context.Request.Path, context.Request.QueryString)), data);
};
});
spa.Options.StartupTimeout = new System.TimeSpan(0, 3, 0);
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
catch (Exception ex)
{
throw ex;
}
}
protected void GetSupplyData(HttpContext context, Uri uri, IDictionary<string, object> data)
{
var routeBackgroundService = context.RequestServices.GetRequiredService<RouteBackgroundService>();
var path = uri.AbsolutePath;
// Remove forward slash from path.
if (path.Length > 0 && path.Substring(0, 1) == "/")
{
path = path.Substring(1, path.Length - 1);
}
// Does the path match a category?
var selectedCategory = routeBackgroundService.GetCategory(path);
if (selectedCategory != null)
{
data["selectedCategory"] = Map(context, selectedCategory);
// Filter the image categories
var imageCategories = routeBackgroundService.GetImageCategoryByCategory(selectedCategory.Id);
// Now get the images.
var images = routeBackgroundService.GetImageByCategory(imageCategories).Select(s => Map(context, s)).ToList();
if (images != null)
{
data["images"] = JsonConvert.SerializeObject(new PageList<Image>(images, uri, uri.ToPageNumber() ?? 1, 12, 5), Formatting.Indented);
}
}
// Ensure all querystring are added to the data.
var queryData = System.Web.HttpUtility.ParseQueryString(uri.Query);
foreach (var q in queryData.AllKeys)
{
data["querystring_" + q] = queryData[q];
}
}
protected Image Map(HttpContext context, ImageEntity entity)
{
var mapper = context.RequestServices.GetRequiredService<IMapper>();
return mapper.Map<ImageEntity, Image>(entity);
}
protected Category Map(HttpContext context, CategoryEntity entity)
{
var mapper = context.RequestServices.GetRequiredService<IMapper>();
return mapper.Map<CategoryEntity, Category>(entity);
}
}
在 StartUp 类中,有一个 Configure void。在 Configure void 中,有一个 app.UseSpa,您可以在其中配置选项。在 app.UseSpa 中,我使用的是 spa.UsePreRendering。
从服务器加载页面时,它会通过 spa.UsePrerendering 中的 options.SupplyData 运行。options.SupplyData 中的参数之一是 HttpContext 类型的上下文。
但是,当从服务器加载页面时,context.Request.Path 总是返回 index.html,而不管在浏览器中输入的路径如何。因此,如果我输入http://domain/test,我希望 context.Request.Path 显示 /test,但它总是返回 /index.html。我猜它这样做是因为 Angular 应用程序的默认 HTML 页面是 /index.html。
这只发生在使用 AspNetCoreModule 的 IIS 10 中,而不是在 Visual Studio 中使用 IIS Express。
解决方案
为了使客户端路由工作,ASP.NET 应该为所有请求返回 index.html,无论实际路径是什么。否则,我们会收到 404 错误。但是对于预渲染的应用程序,我们确实拥有所有需要的 index.html 文件。
因此,而不是使用
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist/ClientApp";
});
您可以尝试在 public void 中手动设置静态文件路由
Configure(IApplicationBuilder app, IHostingEnvironment env): {
...
}
客户端应用程序的路径:
var fileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "ClientApp", "dist", "ClientApp"));
我们还需要告诉我们的提供者,当我们有斜线结尾但没有指定确切的文件名index.html
时应该提供服务。/
var defOptions = new DefaultFilesOptions();
defOptions.FileProvider = fileProvider;
app.UseDefaultFiles(defOptions);
现在我们应该告诉 SPA 文件应该是使用我们的提供者处理所有请求的服务器。(如果有现有的控制器或 Web API 请求,它们就可以正常工作)
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = fileProvider,
RequestPath = new PathString("")
});
推荐阅读
- go - 使用 GORM 选择相关字段
- reactjs - 如何修复来自'this.props.match.params.id'的axios错误未定义错误的get方法
- python - 通过 scipy.interpolate.griddata 在 n 维网格上插值是不可能的
- python - 如何在pyqt4 python中从QcomboBox中删除重复项
- c# - 刷新下拉值,选择的值不应出现在下一个下拉列表中
- android - 如何在 android 中借助 shape drawable 制作多边形?
- node.js - 未定义错误:检查对象/Json中是否存在字段
- jquery - 如何通过更改 div 区域使 textarea 具有弹性
- sql-server - django:数据库驱动程序不支持现代数据时间类型
- php - 如果在 WooCommerce 中没有付款,X 天后自动取消订单