public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // 生成 swagger 配置的 json 文件 services.AddSwaggerGen(s => { s.SwaggerDoc("v1", new OpenApiInfo { Contact = new OpenApiContact { Name = "Danvic Wang", Url = new Uri("https://yuiter.com"), }, Description = "Template.API - ASP.NET Core 后端接口模板", Title = "Template.API", Version = "v1" });
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 公开 swagger 生成的 json 文件节点 app.UseSwagger();
public async Task Invoke(HttpContext httpContext) { var httpMethod = httpContext.Request.Method; var path = httpContext.Request.Path.Value;
// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL if (httpMethod == "GET" && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$")) { // Use relative redirect to support proxy environments var relativeRedirectPath = path.EndsWith("/") ? "index.html" : $"{path.Split('/').Last()}/index.html";
return new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory); } }
当完成了页面的呈现后,因为一般我们会创建一个单独的类库来实现这些功能,在页面中,可能会包含前后端的数据交互,由于我们在宿主的 API 项目中已经完成了对于路由规则的设定,所以这里只需要在类库中通过 nuget 引用 Microsoft.AspNetCore.Mvc.Core ,然后与 Web API 一样的定义 controller,确保这个中间件在宿主程序的调用位于路由匹配规则之后即可