.Net 6 Angular and Authentication 404 error



我一直在将一个项目从angular 11.net 3.1升级到.net 6 angular 13

我从httpclient访问控制器时遇到问题,返回404错误,我知道模式已更改为新的最小托管模型,但它也表示Generic模型仍然完全受支持。

如果能朝着正确的方向努力,我们将不胜感激。

spa应用程序启动并显示网页,但一旦尝试调用.net控制器,就会返回404错误。我已经对uri进行了硬编码,但仍然得到相同的错误。

由于未被授权,邮递员返回预期的401错误。

升级前一切正常。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILog logger) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseExceptionHandler(exceptionHandlerApp =>
{
exceptionHandlerApp.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
// using static System.Net.Mime.MediaTypeNames;
context.Response.ContentType = Text.Plain;
await context.Response.WriteAsync("An exception was thrown.");
var exceptionHandlerPathFeature =
context.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException) {
await context.Response.WriteAsync(" The file was not found.");
}
if (exceptionHandlerPathFeature?.Path == "/") {
await context.Response.WriteAsync(" Page: Home.");
}
});
});
}
else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.ConfigureExceptionHandler(logger);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseCors();
app.UseSecurityHeaders(env.IsDevelopment());

app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapHub<SignalrCartHub>("/signalrCartHub");
endpoints.MapControllers();
});

app.UseSpa(spa => {
// spa.ApplicationBuilder.UseCors(ApplicationCors);
spa.Options.SourcePath = "ClientApp";
spa.Options.StartupTimeout = new TimeSpan(0, 5, 0);
if (env.IsDevelopment()) {
spa.UseAngularCliServer(npmScript: "start");
//spa.UseProxyToSpaDevelopmentServer("http://localhost:5100");
}
});

}
public void ConfigureServices(IServiceCollection services) {

services.Configure<IISOptions>(iis => iis.ForwardClientCertificate = false);
services.AddSignalR();
services.AddRazorPages().AddMvcOptions(options => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddNewtonsoftJson();
services.AddAuthorization(options => {
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});

services.AddMvc(options => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; });

services.AddCors(options =>
options.AddPolicy(ApplicationCors, policy => {
string[] origins = Configuration.GetSection("Cors.Origins").Get<string[]>();
policy.WithOrigins(origins).SetIsOriginAllowedToAllowWildcardSubdomains();
policy.AllowAnyMethod();
policy.AllowAnyHeader();
}));
services.AddSpaStaticFiles(x => x.RootPath = "ClientApp/dist");
services.AddHttpClient();
services.AddAutoMapper(typeof(Startup));

AddAuthentication(services);
var endpointSection = Configuration.GetSection("Endpoints");
services.Configure<AppSettings>(endpointSection);
var connectionInfo = SetDatabase(services);
connectionInfo.DevMode = isDevMode();
AddDependancyInjection(services, connectionInfo);
}

private void AddAuthentication(IServiceCollection services) {
bool proxy = Configuration.GetValue<bool>("Proxy:Enabled");
services.AddAuthentication(x => {
x.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, cookie => {
cookie.SessionStore = new MemoryCacheTicketStore();
cookie.ExpireTimeSpan = new TimeSpan(0, 15, 0);
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, oidc => {
oidc.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// oidc.ReturnUrlParameter = Configuration["Authentication:Return"];
oidc.Authority = Configuration["Authentication:Authority"];
oidc.ResponseType = Configuration["Authentication:ResponseType"];
oidc.ClientId = Configuration["Authentication:ClientId"];
string secret = Configuration["Authentication:ClientSecret"];
oidc.AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost;
if (secret == null) throw new ArgumentNullException(nameof(secret));
oidc.ClientSecret = secret;
oidc.Scope.Clear();
oidc.Scope.Add("openid");
oidc.Scope.Add("profile");
oidc.Scope.Add("email");
oidc.Scope.Add("phone");
oidc.Scope.Add("applications");
oidc.Scope.Add("permissions");
oidc.SaveTokens = true;
oidc.GetClaimsFromUserInfoEndpoint = true;
oidc.AccessDeniedPath = new PathString("/errorSignOn/index");
oidc.TokenValidationParameters = new TokenValidationParameters {
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role
};

OnAuthenticationFailed(oidc);
OnRemoteFailure(oidc);
OnRedirectToIdentityProvider(oidc);
//OnUserInformationReceived(services, oidc);
BackchannelHttpHandler(oidc);
});
}

[Route("api/[controller]")]
[ApiController]
[Authorize]

public class TenantController : ControllerBase {
...
[HttpGet]
[Route("getappdetails")]
public async Task<IActionResult> GetAppDetails() {
...
}
}

错误

加载资源失败:服务器的响应状态为404((.main.js:1错误HTTP:::

无法获取/app/Tenant/getuserdetails

headers:wo{normalizedNames:Map(0(,lazyUpdate:null,lazyInit:ƒ}

消息:"的Http失败响应https://localhost:5001/api/Tenant/getuserdetails:404

url:"https://localhost:5001/api/Tenant/getuserdetails">

我有一个的旧引用

PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" 

删除它解决了这个问题。

最新更新