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:
lchen committed 2026-10-21 14:11:15 +08:00
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.");
}
}