我目前正在开发一个 ASP.NET 项目,其中使用 ASP.NET Identity 来管理用户帐户。我的网络应用程序中还包含一个 API。我当前的问题是,当客户端发出未经过身份验证或授权的 API 请求时,它们会被重定向到登录/禁止页面。但是,我希望此类 API 请求返回 JSON 错误,而不是将用户重定向到登录页面。谁能帮助我如何在 ASP.NET 应用程序中自定义此行为?我需要配置任何特定的中间件或设置才能实现此行为吗?任何帮助或建议将不胜感激。
在你后续的描述中,我理解你了
想要让 API 请求返回 JSON 错误而不是 将用户重定向到登录页面
在我的选择中,我建议您可以创建一个中间件来处理 API 请求和网页请求:
public class ApiRequestMiddleware
{
private readonly RequestDelegate _next;
public ApiRequestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Path.StartsWithSegments("/api"))
{
try
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/json";
var errorResponse = new
{
message = "Unauthorized API requests",
error = "Authentication failed"
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
}
catch (Exception ex)
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
var errorResponse = new
{
message = "serve error",
error = ex.Message
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
}
}
else
{
await _next(context);
}
}
}