ASP.NET Core 8的 Web API在 Ajax响应中不显示异常信息

前端开发 2026-07-08

我接手了一个简单的ASP.NET Core 8 Web API应用,但一直没法弄清楚为什么在我的ajax响应中收不到预期的异常消息。前端是一个React应用。

以下是 Program.cs 的完整内容:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSpaStaticFiles(c => {
    c.RootPath = "ClientApp/build";
});
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);

var app = builder.Build();
/* this was apparently causing issues with my exception being ignored and always returning 200 responses so I removed it
if (app.Environment.IsDevelopment()) {
    app.UseDeveloperExceptionPage();
} else {
    app.UseExceptionHandler("/Error");
}
*/
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();

app.UseEndpoints(e => {
    e.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}"
    );
});
app.UseSpa(s => {
    s.Options.SourcePath = "ClientApp";
    if (app.Environment.IsEnvironment("Local")) {
        s.UseReactDevelopmentServer(npmScript: "start");
    }
});

await app.RunAsync();

我的控制器端点是这样的:

[HttpGet]
[Route("whatever/endpoint1")]
public ResultClass GetStuff(string query) 
{
    throw new BadHttpRequestException("There was an error");
}

无论我用curl、浏览器还是其他方式访问这个端点,我都会得到一个400的响应,响应体为空。没有文本,没有json,什么也没有。

于是我想算了,自己来写,在控制器中这样做:

public ResultClass GetStuff(string query) 
{
    Response.StatusCode = 500;
    Response.WriteAsync("This is an error", System.Text.ASCIIEncoding.ASCII);
    return null;
}

现在我得到一个500,而不是我给出的字符串,而是它被表示为一个base64编码的字符串:

atob('VGhpcyBpcyBhbiBlcnJvcg==') == 'This is an error'

有谁能解释这是怎么回事吗?

  1. 为什么服务器会把我的异常消息从响应中剥离?
  2. 为什么直接把字符串写入响应会把它编码成base64?关于 WriteAsync 的文档并没有提到以任何方式对其进行编码。

解决方案

与其:

  • 直接抛出异常,这会导致500 Internal Server Error状态码
  • 手动组装响应

我建议使用 IActionResultActionResult<T>,以便由MVC管道正确处理响应序列化。

[HttpGet]
[Route("whatever/endpoint1")]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult GetStuff(string query) 
{
    return BadRequest(new { Error = "There was an error" });
}

请注意,ASP.NET Core默认使用 camelCase 进行序列化。

假设你使用的是 fetch API,你应该会看到如下错误信息:

const response = await fetch('/whatever/endpoint1?query=<query value>');

// Handle response status code is not 2XX
if (!response.ok) {
  const body = await response.json();
  console.log(body.error); 

  return;
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章