using Microsoft.Extensions.FileProviders;
using System.Net;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();


string IDentityIp = builder.Configuration["IDentity:IP"].ToString();
string IDentityPort = builder.Configuration["IDentity:Port"].ToString();
string IDentityAPIName = builder.Configuration["IDentity:APIName"].ToString();

string ServicePort = builder.Configuration["Service:Port"].ToString();
builder.WebHost.UseUrls("http://*:" + ServicePort + "");

var app = builder.Build();



// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();

app.UseRouting();


//自定义默认主页

DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
defaultFilesOptions.DefaultFileNames.Clear();
defaultFilesOptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defaultFilesOptions);
app.UseStaticFiles();

/* 兼容VUE宿主使用 可以防止出现404的错误 */
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
               Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")
           ),
    ServeUnknownFileTypes = true // 允许处理未知文件类型
});

// 如果非API请求,则重定向到Vue应用程序的入口文件
app.Run(async (context) =>
{
    context.Response.ContentType = "text/html";
    await context.Response.SendFileAsync(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "index.html"));
});
/* 兼容VUE宿主使用 可以防止出现404的错误 */

// 自定义404错误处理
app.UseStatusCodePages(async context =>
{
    // 检查状态码是否为404
    if (context.HttpContext.Response.StatusCode == (int)HttpStatusCode.NotFound)
    {
        // 可以自定义响应,比如返回JSON或者重定向到另一个页面
        //context.HttpContext.Response.ContentType = "text/plain";
        //await context.HttpContext.Response.WriteAsync("自定义的404错误信息");

        // 设置响应为200状态码,以隐藏404错误
        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;

        // 重定向到index.html
        context.HttpContext.Response.Redirect("index.html");
    }
});

app.UseAuthorization();

app.MapRazorPages();

app.Run();

posted on 2025-02-27 08:59  woody.wu  阅读(77)  评论(0)    收藏  举报