Skip to content

Using middleware in asp net Core 8.0 #57025

Open

Description

This issue has been moved from a ticket on Developer Community.


I have a simpe asp core 8.0 application

with a startup.cs

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
{
services. AddControllers();
services. AddEndpointsApiExplorer();
services. AddSwaggerGen();
DiConfiguration.RegisterServices(services);
services. AddScoped<IBookRepository, BookRepository>();
services. AddScoped<IAuthorRepository, AuthorRepository>();
services. AddDbContext();

//services. AddExceptionHandler(options =>
//{
// options. ExceptionHandlingPath = new PathString(“/Error”);
//});

services. AddIdentity<IdentityUser, IdentityRole>(options =>
{
options. SignIn.RequireConfirmedAccount = false;
}). AddEntityFrameworkStores();

services. ConfigureApplicationCookie(options =>
{
options.Cookie.Name = “auth_cookie”;
options. Cookie.SameSite = SameSiteMode.None;
options. Events.OnRedirectToLogin = context =>
{
context. Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
options. Events.OnRedirectToAccessDenied = context =>
{
context. Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};

});
services. AddScoped();
}
public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime
, ApplicationDbContext context, IdentitySeed IdentitySeed)
{
context. Database.EnsureCreated();
app. UseSwagger();
app. UseSwaggerUI();

app. UseHttpsRedirection();
app. UseRouting();
app. UseMiddleware();
app. UseExceptionHandler(“/error”);
app. UseAuthentication();
app. UseAuthorization();
app. UseEndpoints(endpoint =>
{
endpoint. MapControllerRoute(
name: “default”
, pattern: “{controller}/{action=Index}/{id}”);
});

IdentitySeed.Seed(). Wait();
}

which creates following error:

System.InvalidOperationException: "An error occurred when configuring the exception handler middleware. Either the 'ExceptionHandlingPath' or the 'ExceptionHandler' property must be set in 'UseExceptionHandler()'. Alternatively, set one of the aforementioned properties in 'Startup.ConfigureServices' as follows: 'services. AddExceptionHandler(options => { ... });' or configure to generate a 'ProblemDetails' response in 'service. AddProblemDetails()'."

addnig

services. AddExceptionHandler(options =>
{
options. ExceptionHandlingPath = new PathString(“/Error”);
});

Lets the program run as expected, but the middleware isn’t called any more, as every error ends in a 500

According to Copilot

app. UseExceptionHandler(“/error”);

should do the same as the lines in services, but the error remains poping up

my middleware has a method too catch all unknown errors

catch (Exception ex)
{
context. Response.ContentType = “application/problem+json”;
context. Response.StatusCode = StatusCodes.Status500InternalServerError;

var problemdetail = new ProblemDetails()
{
Status = StatusCodes.Status500InternalServerError,
Detail = ex. Message,
Instance = string. Empty,
Title = “Internal Server Error - something went wrongt”,
Type = string. Empty
};

var problemDetailJson = JsonConvert.SerializeObject(problemdetail);
await context. Response.WriteAsync(problemDetailJson);

}

So the question remains, even with a exception middleware, why do i need a ExceptionHandlingPath at all.

And if i need it, where can i add it without interfering in my middleware.


Original Comments

Feedback Bot on 7/18/2024, 10:02 PM:

(private comment, text removed)


Original Solutions

(no solutions)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Author: Migration Bot 🤖The issue was created by a issue mover bot. The author may not be the actual author.area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions