asp.net-core-mvc - ASP.NET Core 5 MVC,未授权的 JSON 响应
问题描述
我有一个使用 ASP.NET Core MVC 为 .NET 5 配置的站点。我的一个控制器返回 JSON 结果,需要用户经过身份验证才能访问。
当我使用经过身份验证的用户调用它们时,它会从控制器正确返回 JSON 结果。
当我称他们未经身份验证时,我会被重定向到我的登录页面。对于预期的 JSON 响应,这不是正确的响应。
当用户无权访问 ASP.NET Core MVC 控制器中的 JSON 响应时,返回未授权(HTTP 401)的正确方法是什么?
我希望我的客户端 AJAX 处理程序捕获 401 代码并适当地处理它,而不是在它期望 JSON 内容类型时返回 HTML 响应。
控制器中的 JSON 操作
[Authorize]
public IActionResult JsonTest()
{
return Json(new { Status = "Success", Message = "Test", IntId = 100 });
}
和简单的身份验证设置
using jsontest2.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
当您使用授权调用 JsonTest 操作时,它会正确返回 JSON 结果,当您未登录时,我期望 401 我会重定向 302 到登录页面
解决方案
推荐阅读
- python - 将函数内部的元组转换为全局值
- mysql - 带有快速查询的Mysql返回null
- javascript - ESLint no-undef 规则:另一个文件中的许多函数
- java - Liquibase:链接来自测试的主要 yaml 变更日志
- java - 重启 Linux 应用程序后 MySQL 表为空
- lets-encrypt - certbot 和 certbot-auto 之间的区别
- c# - 如何使用 c# 通过 SlackAPI 上传文件 - 没有图像 - 并同时将其评论到 Slack
- vuejs2 - Here Maps 使用 Vue 时将信息气泡添加到地图
- python - 在视图装饰器中获取经过身份验证的用户
- spring - 在 Hibernate 多对多映射中需要以下场景的解决方案