首页 > 解决方案 > 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 到登录页面

标签: asp.net-core-mvc.net-5

解决方案


推荐阅读