initial version.
feat: automatically run vite dev server when in Debugger mode. feat: supports hotreload on both js frontend and .net backend.
This commit is contained in:
1 parent
f925e00540
commit
5c81ed18b2
25 files changed
+743
No files matched your search
@@ -0,0 +1,21 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace WebApplication1.Controllers;
|
||||
|
||||
[Route("api")]
|
||||
[ApiController]
|
||||
[ApiExceptionFilter]
|
||||
public class ApiController : SiteControllerBase
|
||||
{
|
||||
[Route("detail")]
|
||||
[HttpGet]
|
||||
[ResponseCache(CacheProfileName = "NoCache")]
|
||||
public ApiResult<DetailItem> GetDetail(int id)
|
||||
{
|
||||
//throw new PermissionException(500, errorMessage: "test error1");
|
||||
//throw new ApiException(12, "test api exception.");
|
||||
return new DetailItem(id, "Test title");
|
||||
}
|
||||
}
|
||||
|
||||
public record DetailItem(int Id, string Name);
|
||||
@@ -0,0 +1,127 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace WebApplication1.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// API 异常过滤器
|
||||
/// </summary>
|
||||
class ApiExceptionFilterAttribute : ExceptionFilterAttribute
|
||||
{
|
||||
public ApiExceptionFilterAttribute()
|
||||
{
|
||||
Order = 1;
|
||||
}
|
||||
|
||||
public override void OnException(ExceptionContext context)
|
||||
{
|
||||
var ex = context.Exception;
|
||||
|
||||
if (ex is PermissionException pex)
|
||||
{
|
||||
// 如果为权限异常则修改返回状态码
|
||||
context.HttpContext.Response.StatusCode = pex.StatusCode;
|
||||
}
|
||||
|
||||
ExceptionResult result;
|
||||
if (ex is ApiException aex)
|
||||
{
|
||||
#if DEBUG
|
||||
// 调试环境带上堆栈信息
|
||||
result = new ExceptionResult(aex.ErrorCode, aex.ToString());
|
||||
#else
|
||||
result = new ExceptionResult(aex);
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
result = new ExceptionResult(ex);
|
||||
}
|
||||
|
||||
context.Result = new JsonResult(result);
|
||||
context.ExceptionHandled = true;
|
||||
}
|
||||
|
||||
public override Task OnExceptionAsync(ExceptionContext context)
|
||||
{
|
||||
OnException(context);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 页面异常过滤器
|
||||
/// </summary>
|
||||
class PageExceptionFilterAttribute : ExceptionFilterAttribute
|
||||
{
|
||||
public override void OnException(ExceptionContext context)
|
||||
{
|
||||
OnExceptionAsync(context).Wait();
|
||||
}
|
||||
|
||||
public override async Task OnExceptionAsync(ExceptionContext context)
|
||||
{
|
||||
var ex = context.Exception;
|
||||
int statusCode = 500;
|
||||
int errorCode = -1;
|
||||
string errorMessage;
|
||||
switch (ex)
|
||||
{
|
||||
case ApiException aex:
|
||||
if (aex is PermissionException pex)
|
||||
{
|
||||
// 如果为权限异常则修改返回状态码
|
||||
statusCode = pex.StatusCode;
|
||||
}
|
||||
errorCode = aex.ErrorCode;
|
||||
errorMessage = errorCode switch
|
||||
{
|
||||
ApiException.AUTHORIZED_ERROR => "You are not authorized yet.",
|
||||
ApiException.PARAMETER_ERROR => "The server could not understand the request due to invalid parameters.",
|
||||
ApiException.PERMISSION_ERROR => "You have no right to access this page.",
|
||||
_ => "An unknown error occurred."
|
||||
};
|
||||
break;
|
||||
|
||||
case System.Net.WebException:
|
||||
case EndOfStreamException:
|
||||
errorMessage = "Network connection is failed.";
|
||||
break;
|
||||
|
||||
case TaskCanceledException:
|
||||
case OperationCanceledException:
|
||||
errorMessage = "Operation timeout, maybe caused by the network, please try again later.";
|
||||
break;
|
||||
|
||||
default:
|
||||
errorMessage = "An unknown error occurred.";
|
||||
break;
|
||||
}
|
||||
|
||||
// deprecated: relative path
|
||||
//var prefix = context.HttpContext.Request.Path.Value?.Trim('/');
|
||||
//if (!string.IsNullOrEmpty(prefix))
|
||||
//{
|
||||
// int segmentCount = prefix.Split('/', StringSplitOptions.RemoveEmptyEntries).Length;
|
||||
// prefix = string.Concat(Enumerable.Repeat("../", segmentCount));
|
||||
//}
|
||||
|
||||
var helper = context.HttpContext.RequestServices.GetRequiredService<ViteHelper>();
|
||||
var html = await helper.RenderAsync(
|
||||
context.HttpContext.Request.PathBase,
|
||||
"Templates/error.html",
|
||||
"src/pages/error.ts",
|
||||
new ApiErrorResult(errorCode, errorMessage),
|
||||
new() { ["Title"] = "Error Page" });
|
||||
|
||||
context.Result = new ContentResult
|
||||
{
|
||||
Content = html,
|
||||
ContentType = "text/html; charset=utf-8",
|
||||
StatusCode = statusCode
|
||||
};
|
||||
context.ExceptionHandled = true;
|
||||
}
|
||||
}
|
||||
|
||||
record ApiErrorResult(int ErrorCode, string ErrorMessage);
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace WebApplication1.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// 异常结果类
|
||||
/// </summary>
|
||||
public class ExceptionResult : ApiResult<object>
|
||||
{
|
||||
public ExceptionResult(int errorCode, string errorMessage)
|
||||
{
|
||||
ErrorCode = errorCode;
|
||||
ErrorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public ExceptionResult(ApiException exception) : this(exception.ErrorCode, exception.Message) { }
|
||||
|
||||
public ExceptionResult(Exception exception) : this(-1, exception.Message) { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// API 返回结果类
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="result"></param>
|
||||
public class ApiResult<T>(T result = default)
|
||||
{
|
||||
public int ErrorCode { get; set; }
|
||||
public string ErrorMessage { get; set; }
|
||||
public string ResourceId { get; set; }
|
||||
public T Result { get; set; } = result;
|
||||
public object Tag { get; set; }
|
||||
|
||||
public static implicit operator ApiResult<T>(T result) => new(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// API 业务异常
|
||||
/// </summary>
|
||||
/// <param name="errorCode">错误码</param>
|
||||
/// <param name="errorMessage">错误信息</param>
|
||||
public class ApiException(int errorCode, string errorMessage = null) : Exception(errorMessage)
|
||||
{
|
||||
public const int UNKNOWN_ERROR = -1;
|
||||
public const int AUTHORIZED_ERROR = 1;
|
||||
public const int PARAMETER_ERROR = 2;
|
||||
public const int PERMISSION_ERROR = 3;
|
||||
|
||||
public int ErrorCode { get; } = errorCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 权限异常
|
||||
/// </summary>
|
||||
/// <param name="statusCode">状态码</param>
|
||||
/// <param name="errorCode">错误码</param>
|
||||
/// <param name="errorMessage">错误信息</param>
|
||||
public class PermissionException(int statusCode, int errorCode = ApiException.AUTHORIZED_ERROR, string errorMessage = null) : ApiException(errorCode, errorMessage)
|
||||
{
|
||||
public int StatusCode { get; } = statusCode;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace WebApplication1.Controllers;
|
||||
|
||||
[Route("")]
|
||||
public class DefaultController(ViteHelper vite) : SiteControllerBase(vite)
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get()
|
||||
{
|
||||
if (!Request.Path.HasValue || !Request.Path.Value.EndsWith('/'))
|
||||
{
|
||||
return RedirectPermanent($"{Request.PathBase}/{Request.QueryString}");
|
||||
}
|
||||
|
||||
var html = await viteHelper.RenderAsync(
|
||||
Request.PathBase,
|
||||
"Templates/main.html",
|
||||
"src/main.ts",
|
||||
new() { ["Title"] = "Home Page" });
|
||||
|
||||
return Content(html, "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
[Route("test/error")]
|
||||
[HttpGet]
|
||||
[ResponseCache(CacheProfileName = "NoCache")]
|
||||
public IActionResult GetTest()
|
||||
{
|
||||
throw new PermissionException(400, errorMessage: "This is a test permission exception.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.ResponseCompression;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json.Serialization;
|
||||
using WebApplication1.Controllers;
|
||||
|
||||
namespace WebApplication1;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
#if DEBUG
|
||||
if (Debugger.IsAttached)
|
||||
{
|
||||
var sourcePath = Path.Combine(AppContext.BaseDirectory, "../../../Source");
|
||||
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "cmd.exe",
|
||||
Arguments = $"/k \"cd /d \"{sourcePath}\" && npm run dev:vite\"",
|
||||
UseShellExecute = true
|
||||
});
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
#endif
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddSingleton<ViteHelper>();
|
||||
|
||||
builder.Services
|
||||
.AddControllers((options) =>
|
||||
{
|
||||
options.CacheProfiles.Add("Default", new CacheProfile
|
||||
{
|
||||
Duration = 2592000,
|
||||
Location = ResponseCacheLocation.Any,
|
||||
NoStore = false
|
||||
});
|
||||
options.CacheProfiles.Add("NoCache", new CacheProfile
|
||||
{
|
||||
Location = ResponseCacheLocation.None,
|
||||
NoStore = true
|
||||
});
|
||||
if (!builder.Environment.IsDevelopment())
|
||||
{
|
||||
options.Filters.Add<PageExceptionFilterAttribute>();
|
||||
}
|
||||
})
|
||||
.AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
|
||||
});
|
||||
|
||||
builder.Services
|
||||
.AddResponseCompression(options =>
|
||||
{
|
||||
options.Providers.Add<BrotliCompressionProvider>();
|
||||
options.Providers.Add<GzipCompressionProvider>();
|
||||
options.MimeTypes = ["application/json"];
|
||||
options.EnableForHttps = true;
|
||||
})
|
||||
.Configure<BrotliCompressionProviderOptions>(options =>
|
||||
{
|
||||
options.Level = CompressionLevel.Optimal;
|
||||
})
|
||||
.AddResponseCaching();
|
||||
|
||||
builder.WebHost.UseIIS();
|
||||
|
||||
var app = builder.Build();
|
||||
app.UseStaticFiles();
|
||||
|
||||
#if DEBUG
|
||||
app.UseDeveloperExceptionPage();
|
||||
#endif
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
app.UseRouting();
|
||||
app.UseAuthorization();
|
||||
app.UseResponseCompression();
|
||||
app.UseResponseCaching();
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "http://localhost:5284"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
},
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:52167/",
|
||||
"sslPort": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace WebApplication1;
|
||||
|
||||
public abstract class SiteControllerBase(ViteHelper vite) : ControllerBase
|
||||
{
|
||||
protected readonly ViteHelper viteHelper = vite;
|
||||
|
||||
public SiteControllerBase() : this(null) { }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import js from "@eslint/js";
|
||||
import globals from "globals";
|
||||
import tseslint from "typescript-eslint";
|
||||
import { defineConfig } from "eslint/config";
|
||||
|
||||
export default defineConfig([
|
||||
tseslint.configs.recommended,
|
||||
{
|
||||
files: ["**/*.{js,mjs,cjs,ts,mts,cts}"],
|
||||
plugins: { js },
|
||||
extends: ["js/recommended"],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
__SITE_PATH__: 'readonly',
|
||||
__SERVER_DATA__: 'readonly'
|
||||
}
|
||||
},
|
||||
// add your custom rules here
|
||||
rules: {
|
||||
// 'indent': ['error', 4, {
|
||||
// 'SwitchCase': 1
|
||||
// }],
|
||||
"indent": "off",
|
||||
"linebreak-style": "off",
|
||||
"max-len": "off",
|
||||
//"no-console": [
|
||||
// "error",
|
||||
// { "allow": ["warn", "error"] }
|
||||
//],
|
||||
"no-console": "warn",
|
||||
"no-continue": "off",
|
||||
"no-debugger": "error",
|
||||
"no-empty": "off",
|
||||
"no-undef": "off",
|
||||
"no-unused-vars": "off",
|
||||
"no-redeclare": "off",
|
||||
"no-mixed-operators": [
|
||||
"error",
|
||||
{
|
||||
"groups": [["&&", "||"]]
|
||||
}
|
||||
],
|
||||
//"no-nested-ternary": "off",
|
||||
//"no-param-reassign": "off",
|
||||
//"no-underscore-dangle": "off",
|
||||
//"no-void": "off",
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
"@typescript-eslint/triple-slash-reference": "off",
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "source",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev:vite": "vite",
|
||||
"build": "eslint && vite build"
|
||||
},
|
||||
"author": "Foresight Intelligence",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@types/node": "^26.6.5",
|
||||
"eslint": "^10.13.0",
|
||||
"globals": "^17.13.0",
|
||||
"typescript-eslint": "^8.72.0",
|
||||
"vite": "^8.3.4"
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
interface DetailItem {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/// <reference path="./global.d.ts" />
|
||||
|
||||
export interface ApiSuccess<T> {
|
||||
errorCode: 0;
|
||||
result: T;
|
||||
tag?: unknown;
|
||||
}
|
||||
|
||||
export interface ApiFailure {
|
||||
errorCode: number;
|
||||
errorMessage?: string;
|
||||
resourceId?: string;
|
||||
tag?: unknown;
|
||||
}
|
||||
|
||||
export type ApiResult<T = unknown> = ApiSuccess<T> | ApiFailure;
|
||||
|
||||
export class ApiError extends Error {
|
||||
public errorCode: number;
|
||||
public errorMessage?: string;
|
||||
|
||||
constructor(errorCode: number, errorMessage?: string) {
|
||||
super(errorMessage);
|
||||
this.name = 'ApiError';
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = errorMessage;
|
||||
// Object.setPrototypeOf(this, ApiError.prototype);
|
||||
}
|
||||
|
||||
override toString(): string {
|
||||
return `[${this.name}]: ${this.errorMessage} (${this.errorCode})`;
|
||||
}
|
||||
|
||||
get [Symbol.toStringTag](): string {
|
||||
return 'ApiError';
|
||||
}
|
||||
}
|
||||
|
||||
export function isSuccess<T>(res: ApiResult<T>): res is ApiSuccess<T> {
|
||||
return res.errorCode === 0;
|
||||
}
|
||||
|
||||
export async function fetchApi<T>(url: string): Promise<T> {
|
||||
const response = await fetch(url);
|
||||
const json: ApiResult<T> = await response.json();
|
||||
|
||||
if (!isSuccess(json)) {
|
||||
throw new ApiError(json.errorCode, json.errorMessage);
|
||||
}
|
||||
|
||||
return json.result;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApiError, fetchApi } from './helper';
|
||||
|
||||
const container = document.querySelector('#main');
|
||||
|
||||
if (container) {
|
||||
try {
|
||||
const detail = await fetchApi<DetailItem>('api/detail?id=11');
|
||||
container.innerHTML = `
|
||||
<div style="background: #f0f0f0; padding: 15px; border-radius: 12px">
|
||||
<h3>Title: ${detail.name}</h3>
|
||||
<p>ID: ${detail.id}</p>
|
||||
</div>
|
||||
`;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError) {
|
||||
container.innerHTML = `<p>${e.errorCode}</p><pre>${e.errorMessage}</pre>`;
|
||||
} else {
|
||||
container.innerHTML = '<pre>unknown error</pre>';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { ApiError } from "../helper";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__SERVER_DATA__: ApiError
|
||||
}
|
||||
}
|
||||
|
||||
const errorContainer = document.querySelector('#error');
|
||||
|
||||
if (errorContainer instanceof HTMLElement) {
|
||||
const err = window.__SERVER_DATA__;
|
||||
errorContainer.innerText = `${err.errorCode}: ${err.errorMessage}`;
|
||||
}
|
||||
|
||||
export { }
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"include": [
|
||||
"src/**/*.ts",
|
||||
"vite.config.ts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"types": [ "node" ],
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import path from 'node:path';
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: 5173,
|
||||
cors: true,
|
||||
strictPort: true
|
||||
},
|
||||
build: {
|
||||
outDir: path.resolve(import.meta.dirname, '../wwwroot/dist'),
|
||||
emptyOutDir: true,
|
||||
manifest: true,
|
||||
rollupOptions: {
|
||||
input: {
|
||||
main: path.resolve(import.meta.dirname, 'src/main.ts'),
|
||||
error: path.resolve(import.meta.dirname, 'src/pages/error.ts')
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title><!-- @Title --></title>
|
||||
<!-- @ViteAssets -->
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<h1><!-- @Title --></h1>
|
||||
<div id="error"></div>
|
||||
</div>
|
||||
<!-- @ServerData -->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title><!-- @Title --></title>
|
||||
<!-- @ViteAssets -->
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<h1><!-- @Title --></h1>
|
||||
<div id="main"></div>
|
||||
</div>
|
||||
<!-- @ServerData -->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,71 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WebApplication1;
|
||||
|
||||
#if DEBUG
|
||||
public class ViteHelper(IOptions<JsonOptions> options)
|
||||
{
|
||||
#else
|
||||
public class ViteHelper(IWebHostEnvironment env, IOptions<JsonOptions> options)
|
||||
{
|
||||
readonly string rootPath = env.WebRootPath ?? Path.Combine(AppContext.BaseDirectory, "wwwroot");
|
||||
#endif
|
||||
readonly JsonSerializerOptions jsonOptions = options.Value.JsonSerializerOptions;
|
||||
|
||||
public Task<string> RenderAsync(string pathBase, string templatePath, string entryScript, Dictionary<string, string> stringTokens = null)
|
||||
{
|
||||
return RenderInternalAsync(pathBase, templatePath, entryScript, null, stringTokens);
|
||||
}
|
||||
|
||||
public Task<string> RenderAsync<T>(string pathBase, string templatePath, string entryScript, T serverData = default, Dictionary<string, string> stringTokens = null)
|
||||
{
|
||||
return RenderInternalAsync(pathBase, templatePath, entryScript, serverData, stringTokens);
|
||||
}
|
||||
|
||||
async Task<string> RenderInternalAsync(string pathBase, string templatePath, string entryScript, object serverData = null, Dictionary<string, string> stringTokens = null)
|
||||
{
|
||||
var path = Path.Combine(AppContext.BaseDirectory, templatePath);
|
||||
var html = await File.ReadAllTextAsync(path);
|
||||
|
||||
if (stringTokens is not null)
|
||||
{
|
||||
foreach (var token in stringTokens)
|
||||
{
|
||||
html = html.Replace($"<!-- @{token.Key} -->", token.Value);
|
||||
}
|
||||
}
|
||||
|
||||
html = html.Replace("<!-- @ServerData -->", serverData is not null ?
|
||||
$"<script>window.__SERVER_DATA__={JsonSerializer.Serialize(serverData, jsonOptions)};</script>" :
|
||||
"");
|
||||
|
||||
#if DEBUG
|
||||
var viteAssets = $"""
|
||||
<script type="module" src="http://localhost:5173/@vite/client"></script>
|
||||
<script type="module" src="http://localhost:5173/{entryScript}"></script>
|
||||
""";
|
||||
#else
|
||||
var manifestPath = Path.Combine(rootPath, "dist", ".vite", "manifest.json");
|
||||
var manifestJson = await File.ReadAllTextAsync(manifestPath);
|
||||
using var manifest = JsonDocument.Parse(manifestJson);
|
||||
|
||||
var entry = manifest.RootElement.GetProperty(entryScript);
|
||||
var jsFile = entry.GetProperty("file").GetString();
|
||||
|
||||
var viteAssets = $"<base href=\"{pathBase}/\"/>" +
|
||||
$"<script type=\"module\" src=\"dist/{jsFile}\"></script>";
|
||||
|
||||
if (entry.TryGetProperty("css", out var cssArray))
|
||||
{
|
||||
foreach (var css in cssArray.EnumerateArray())
|
||||
{
|
||||
viteAssets += $"\n<link rel=\"stylesheet\" href=\"dist/{css.GetString()}\"/>";
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return html.Replace("<!-- @ViteAssets -->", viteAssets);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>disable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<OutputType>Exe</OutputType>
|
||||
<StaticWebAssetsEnabled>false</StaticWebAssetsEnabled>
|
||||
<SpaRoot>Source\</SpaRoot>
|
||||
<FrontendStampFile>$(BaseIntermediateOutputPath)$(Configuration)\frontend_build.stamp</FrontendStampFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Remove="Source\*.json" />
|
||||
<None Include="Source\*.json" />
|
||||
<None Update="Templates\**\*.html">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="wwwroot\dist\.vite\manifest.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrontendInputs Include="$(SpaRoot)src\**"/>
|
||||
<FrontendInputs Include="$(SpaRoot)package.json"/>
|
||||
<FrontendInputs Include="$(SpaRoot)vite.config.ts"/>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="BuildFrontend" BeforeTargets="BeforeBuild"
|
||||
Inputs="@(FrontendInputs)" Outputs="$(FrontendStampFile)">
|
||||
<Message Importance="high" Text="Changes detected. Running npm run build..." />
|
||||
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />
|
||||
<Touch Files="$(FrontendStampFile)" AlwaysCreate="true" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,17 @@
|
||||
@WebApplication1_HostAddress = http://localhost:52167
|
||||
@WebApplication1_ViteAddress = http://localhost:5173
|
||||
|
||||
GET {{WebApplication1_HostAddress}}/api/detail?id=22
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
|
||||
GET {{WebApplication1_HostAddress}}/test/error
|
||||
Accept: text/html
|
||||
|
||||
###
|
||||
|
||||
GET {{WebApplication1_ViteAddress}}/src/main.ts
|
||||
Accept: text/javascript
|
||||
|
||||
###
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
Reference in new issue
Block a user