diff --git a/.gitignore b/.gitignore index ed6d1d2..779fe11 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,9 @@ ## ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore +package-lock.json +*/wwwroot/dist + # User-specific files *.rsuser *.suo diff --git a/WebApplication1.slnx b/WebApplication1.slnx new file mode 100644 index 0000000..549d235 --- /dev/null +++ b/WebApplication1.slnx @@ -0,0 +1,3 @@ + + + diff --git a/WebApplication1/Controllers/ApiController.cs b/WebApplication1/Controllers/ApiController.cs new file mode 100644 index 0000000..5002cbe --- /dev/null +++ b/WebApplication1/Controllers/ApiController.cs @@ -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 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); diff --git a/WebApplication1/Controllers/ApiController.filter.cs b/WebApplication1/Controllers/ApiController.filter.cs new file mode 100644 index 0000000..379971b --- /dev/null +++ b/WebApplication1/Controllers/ApiController.filter.cs @@ -0,0 +1,127 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace WebApplication1.Controllers; + +/// +/// API 异常过滤器 +/// +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; + } +} + +/// +/// 页面异常过滤器 +/// +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(); + 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); diff --git a/WebApplication1/Controllers/ApiController.model.cs b/WebApplication1/Controllers/ApiController.model.cs new file mode 100644 index 0000000..7f83c98 --- /dev/null +++ b/WebApplication1/Controllers/ApiController.model.cs @@ -0,0 +1,59 @@ +namespace WebApplication1.Controllers; + +/// +/// 异常结果类 +/// +public class ExceptionResult : ApiResult +{ + 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) { } +} + +/// +/// API 返回结果类 +/// +/// +/// +public class ApiResult(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 result) => new(result); +} + +/// +/// API 业务异常 +/// +/// 错误码 +/// 错误信息 +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; +} + +/// +/// 权限异常 +/// +/// 状态码 +/// 错误码 +/// 错误信息 +public class PermissionException(int statusCode, int errorCode = ApiException.AUTHORIZED_ERROR, string errorMessage = null) : ApiException(errorCode, errorMessage) +{ + public int StatusCode { get; } = statusCode; +} diff --git a/WebApplication1/Controllers/DefaultController.cs b/WebApplication1/Controllers/DefaultController.cs new file mode 100644 index 0000000..8940c32 --- /dev/null +++ b/WebApplication1/Controllers/DefaultController.cs @@ -0,0 +1,32 @@ +using Microsoft.AspNetCore.Mvc; + +namespace WebApplication1.Controllers; + +[Route("")] +public class DefaultController(ViteHelper vite) : SiteControllerBase(vite) +{ + [HttpGet] + public async Task 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."); + } +} diff --git a/WebApplication1/Program.cs b/WebApplication1/Program.cs new file mode 100644 index 0000000..03e0fa4 --- /dev/null +++ b/WebApplication1/Program.cs @@ -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(); + + 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(); + } + }) + .AddJsonOptions(options => + { + options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + }); + + builder.Services + .AddResponseCompression(options => + { + options.Providers.Add(); + options.Providers.Add(); + options.MimeTypes = ["application/json"]; + options.EnableForHttps = true; + }) + .Configure(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(); + } +} diff --git a/WebApplication1/Properties/launchSettings.json b/WebApplication1/Properties/launchSettings.json new file mode 100644 index 0000000..8715018 --- /dev/null +++ b/WebApplication1/Properties/launchSettings.json @@ -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 + } + } +} \ No newline at end of file diff --git a/WebApplication1/SiteControllerBase.cs b/WebApplication1/SiteControllerBase.cs new file mode 100644 index 0000000..6d28b6b --- /dev/null +++ b/WebApplication1/SiteControllerBase.cs @@ -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) { } +} diff --git a/WebApplication1/Source/eslint.config.js b/WebApplication1/Source/eslint.config.js new file mode 100644 index 0000000..1c14e61 --- /dev/null +++ b/WebApplication1/Source/eslint.config.js @@ -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", + }, + }, +]); diff --git a/WebApplication1/Source/package.json b/WebApplication1/Source/package.json new file mode 100644 index 0000000..af681be --- /dev/null +++ b/WebApplication1/Source/package.json @@ -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" + } +} diff --git a/WebApplication1/Source/src/global.d.ts b/WebApplication1/Source/src/global.d.ts new file mode 100644 index 0000000..b912795 --- /dev/null +++ b/WebApplication1/Source/src/global.d.ts @@ -0,0 +1,4 @@ +interface DetailItem { + id: number; + name: string; +} diff --git a/WebApplication1/Source/src/helper.ts b/WebApplication1/Source/src/helper.ts new file mode 100644 index 0000000..47c01bf --- /dev/null +++ b/WebApplication1/Source/src/helper.ts @@ -0,0 +1,52 @@ +/// + +export interface ApiSuccess { + errorCode: 0; + result: T; + tag?: unknown; +} + +export interface ApiFailure { + errorCode: number; + errorMessage?: string; + resourceId?: string; + tag?: unknown; +} + +export type ApiResult = ApiSuccess | 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(res: ApiResult): res is ApiSuccess { + return res.errorCode === 0; +} + +export async function fetchApi(url: string): Promise { + const response = await fetch(url); + const json: ApiResult = await response.json(); + + if (!isSuccess(json)) { + throw new ApiError(json.errorCode, json.errorMessage); + } + + return json.result; +} diff --git a/WebApplication1/Source/src/main.ts b/WebApplication1/Source/src/main.ts new file mode 100644 index 0000000..c101a95 --- /dev/null +++ b/WebApplication1/Source/src/main.ts @@ -0,0 +1,21 @@ +import { ApiError, fetchApi } from './helper'; + +const container = document.querySelector('#main'); + +if (container) { + try { + const detail = await fetchApi('api/detail?id=11'); + container.innerHTML = ` +
+

Title: ${detail.name}

+

ID: ${detail.id}

+
+ `; + } catch (e) { + if (e instanceof ApiError) { + container.innerHTML = `

${e.errorCode}

${e.errorMessage}
`; + } else { + container.innerHTML = '
unknown error
'; + } + } +} diff --git a/WebApplication1/Source/src/pages/error.ts b/WebApplication1/Source/src/pages/error.ts new file mode 100644 index 0000000..db419e3 --- /dev/null +++ b/WebApplication1/Source/src/pages/error.ts @@ -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 { } diff --git a/WebApplication1/Source/tsconfig.json b/WebApplication1/Source/tsconfig.json new file mode 100644 index 0000000..31a14a7 --- /dev/null +++ b/WebApplication1/Source/tsconfig.json @@ -0,0 +1,11 @@ +{ + "include": [ + "src/**/*.ts", + "vite.config.ts" + ], + "compilerOptions": { + "types": [ "node" ], + "module": "esnext", + "moduleResolution": "bundler" + } +} diff --git a/WebApplication1/Source/vite.config.ts b/WebApplication1/Source/vite.config.ts new file mode 100644 index 0000000..af958df --- /dev/null +++ b/WebApplication1/Source/vite.config.ts @@ -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') + } + } + } +}); \ No newline at end of file diff --git a/WebApplication1/Templates/error.html b/WebApplication1/Templates/error.html new file mode 100644 index 0000000..d0a9826 --- /dev/null +++ b/WebApplication1/Templates/error.html @@ -0,0 +1,16 @@ + + + + + + <!-- @Title --> + + + +
+

+
+
+ + + \ No newline at end of file diff --git a/WebApplication1/Templates/main.html b/WebApplication1/Templates/main.html new file mode 100644 index 0000000..e45c69c --- /dev/null +++ b/WebApplication1/Templates/main.html @@ -0,0 +1,16 @@ + + + + + + <!-- @Title --> + + + +
+

+
+
+ + + \ No newline at end of file diff --git a/WebApplication1/ViteHelper.cs b/WebApplication1/ViteHelper.cs new file mode 100644 index 0000000..d42bfb6 --- /dev/null +++ b/WebApplication1/ViteHelper.cs @@ -0,0 +1,71 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using System.Text.Json; + +namespace WebApplication1; + +#if DEBUG +public class ViteHelper(IOptions options) +{ +#else +public class ViteHelper(IWebHostEnvironment env, IOptions options) +{ + readonly string rootPath = env.WebRootPath ?? Path.Combine(AppContext.BaseDirectory, "wwwroot"); +#endif + readonly JsonSerializerOptions jsonOptions = options.Value.JsonSerializerOptions; + + public Task RenderAsync(string pathBase, string templatePath, string entryScript, Dictionary stringTokens = null) + { + return RenderInternalAsync(pathBase, templatePath, entryScript, null, stringTokens); + } + + public Task RenderAsync(string pathBase, string templatePath, string entryScript, T serverData = default, Dictionary stringTokens = null) + { + return RenderInternalAsync(pathBase, templatePath, entryScript, serverData, stringTokens); + } + + async Task RenderInternalAsync(string pathBase, string templatePath, string entryScript, object serverData = null, Dictionary 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.Value); + } + } + + html = html.Replace("", serverData is not null ? + $"" : + ""); + +#if DEBUG + var viteAssets = $""" + + + """; +#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 = $"" + + $""; + + if (entry.TryGetProperty("css", out var cssArray)) + { + foreach (var css in cssArray.EnumerateArray()) + { + viteAssets += $"\n"; + } + } +#endif + + return html.Replace("", viteAssets); + } +} diff --git a/WebApplication1/WebApplication1.csproj b/WebApplication1/WebApplication1.csproj new file mode 100644 index 0000000..e204d5d --- /dev/null +++ b/WebApplication1/WebApplication1.csproj @@ -0,0 +1,37 @@ + + + + net10.0 + disable + enable + Exe + false + Source\ + $(BaseIntermediateOutputPath)$(Configuration)\frontend_build.stamp + + + + + + + PreserveNewest + + + PreserveNewest + + + + + + + + + + + + + + + + diff --git a/WebApplication1/WebApplication1.http b/WebApplication1/WebApplication1.http new file mode 100644 index 0000000..2304e22 --- /dev/null +++ b/WebApplication1/WebApplication1.http @@ -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 + +### diff --git a/WebApplication1/appsettings.Development.json b/WebApplication1/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/WebApplication1/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/WebApplication1/appsettings.json b/WebApplication1/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/WebApplication1/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/WebApplication1/wwwroot/favicon.ico b/WebApplication1/wwwroot/favicon.ico new file mode 100644 index 0000000..6321ab8 Binary files /dev/null and b/WebApplication1/wwwroot/favicon.ico differ