我的問題是,當我進入我的網站.com/adsadasdsad時,我被重定向到/Error/404,大約20次,直到瀏覽器放棄。 我的代碼是:
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
使用System.Collections.Generic
using System.Collections.Generic;
using System.Linq;
使用System.Threading.Tasks;
命名空間 _projectname
{
公用類 "啟動"。
{
public Startup(IConfiguration configuration)
{
配置 = 配置。
}
public IConfiguration Configuration { get; }
// 這個方法會被運行時呼叫。使用此方法將服務添加到容器中。
public void ConfigureServices(IServiceCollection services)
{
//注冊依賴性
services.AddRazorPages()。
}
// 這個方法被運行時呼叫。使用此方法來配置HTTP請求管道。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
如果(env.IsDevelopment())
{
app.UseDeveloperExceptionPage()。
}
否則
{
app.Use(async (ctx, next) =>
{
await next();
如果(ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
{
/重新執行請求,以便用戶得到錯誤頁面
string originalPath = ctx.Request.Path.Value;
ctx.Items["originalPath"] = originalPath;
ctx.Request.Path="/Error"。
await next();
}
});
// 原文
System.Diagnostics.Debug.WriteLine("bah")。
//app.UseExceptionHandler("/Error/{0}")。
app.UseStatusCodePagesWithRedirects("/Error")。
// 默認的HSTS值是30天。你可能想在生產場景中改變這一點,見https://aka.ms/aspnetcore-hsts。
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting()。
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages()。
});
}
}
}
在上面這段代碼中,我嘗試使用app.UseExceptionHandler和app.UseStatusCodePagesWithRedirects互換,但沒有結果。
我的錯誤控制器:
使用Microsoft.AspNetCore.Mvc;
命名空間_projectname.Error.Mvc
public class ErrorController : Controller
{
[Route("/Error/{statusCode}") ]
public IActionResult HttpStatusCodeHandler(int statusCode)
{
switch (statusCode)
{
case 404:
System.Diagnostics.Debug.WriteLine("bah")。
ViewBag.ErrorMessage("找不到資源。")。
休息。
case 500:
break;
}
回傳View("Error")。
}
}
我不明白我做錯了什么。即使我改變了我的重定向URL,重定向似乎也會回圈,而且斷點在我的Visual Studio 2022預覽版中似乎不起作用。此外,似乎沒有輸出。
我的 launchSettings.json 內容如下:
我的 launchSettings.json 內容如下:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:28725",
"sslPort": 44342
}
},
"組態檔": {
"_34digital.ruhr"。{
"commandName": "專案",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000"。
"environmentalVariables": {
"aspnetcore_environment": "生產"
}
},
"IIS Express": {
"commandName": "IISExpress",
"啟動瀏覽器": true,
"environmentalVariables": {
"aspnetcore_environment": "生產"
}
}
}
}
P.S.是的,我確實有一個共享的Error.cshtml和一個名為 "Error "的檔案夾,里面有404.cshtml和500.cshtml
uj5u.com熱心網友回復:
錯誤在于Error檔案夾不在Pages檔案夾中(facepalm)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331347.html
標籤:
