416 questions
0
votes
1
answer
135
views
Difference between RequestDelegate and Middleware in ASP.NET Core?
I was recently in a technical discussion with a senior developer and was asked:
What is the difference between RequestDelegate and Middleware in ASP.NET Core?
I have already visited the following ...
0
votes
1
answer
151
views
'InvalidOperationException: Unable to resolve service for type' exception thrown while trying to implement exception handling Middleware
I am trying to implement a custom middleware to globally handle exceptions in my ASP.NET Core Web API project. My .NET Core version is 9.0. I created a custom class by extending from IMiddleware.
My ...
0
votes
1
answer
185
views
Durable Function with Global Exception Handler
We have a Durable Function with multiple orchestrators and activities. We would like to use a middleware as global exception handler instead of handling it in every orchestrator/activity. We can catch ...
0
votes
1
answer
350
views
Single app.UseWhen vs multiple app.UseWhen
In ASP .NET Core app want to make one of my controllers sessionless. So I do the following:
app.UseWhen(
context => context.GetRouteValue("controller") is not "SomeValue",
app =&...
0
votes
1
answer
620
views
ASP.NET Core 8 - UseWhen and pass HttpContext as parameter
I needed a custom file provider, and to access a request's HttpContext, I found a solution using IHttpContextAccessor:
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/res", ...
0
votes
1
answer
164
views
UseStaticFiles, set folder dynamically based on host
I need to allow for individual hosts to have their own folder serving static files.
Started out doing like this:
var hosts = cfg.GetSection("AppSettings:AvailableHosts").Get<string[]>()...
2
votes
1
answer
118
views
ASP.NET Core - CORS error when posting the request despite allowing all origins
Whenever I send a POST request to my server from a frontend webpage I've made, the DevTools console throws the error below:
Access to fetch at 'http://127.0.0.1:5000/CreateBooking' from origin 'http:/...
1
vote
1
answer
151
views
Object as a Scoped Service, With Values being Set in Middleware, Sometimes Remains Null
I use the following to create an instance of a class for storing user information during the request:
services.AddScoped<IUserSettings, UserSettings>();
Then I use middleware to set the values ...
0
votes
1
answer
93
views
Process one request and enqueue other requests using Semaphore in Middleware
I am using semaphore to handle one request at a time and enqueue other request and process in sequence. But when I run the code it run first request and drop other request. What I am doing wrong here?...
0
votes
1
answer
100
views
Cannot read request body in HttpRequestTelemetryInitializer
I want to read the Body of incoming requests with the help of my HttpRequestTelemetryInitializer class. Although my GetRequestHeader method works successfully, I get the following error on the
var ...
0
votes
0
answers
74
views
Global error handler for ASP.NET Core application
I am trying to configure a global error handler for my web app.
Configuration
In the Startup.cs Configure method:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app....
0
votes
1
answer
83
views
app.UseStatusCodePagesWithReExecute Does Not Seem to Execute Pipeline Again
In my .NET 7 web site, I've set up the processing pipeline to use UseStatusCodePagesWithReExecute but with a registered middleware in the pipeline returns 404, it correctly returns the 404.cshtml page,...
-1
votes
1
answer
61
views
If Migration is not sent to the database, UseExceptionHandler Middleware will not work. Why?
I added a new property in a entity class. I didn't create migration. After that, I tried to use UseExceptionHandler middleware. It successfully triggered error action method but the view didn't appear....
0
votes
1
answer
1k
views
Best Practices for using middleware in ASP.NET Core Web API for exception handling, authentication, and error logging
I'm working on an ASP.NET Core Web API project and I am trying to implement some global functionalities using middleware. Specifically, I want to handle the following:
Global exception handling: ...
0
votes
1
answer
548
views
ASP.NET Core is logging "request unhandled" even though it is handled by my middleware
I have some middleware which sets a response status code, content type and content (with SendFileAsync) yet the log file contains a debug message from Microsoft.AspNetCore.Hosting.Diagnostics saying &...
0
votes
1
answer
413
views
Access response body in middleware unit test
I have a .net middleware that modifies the response and I'm trying to unit test it. I am able to successfully assert the status code and content type are correct, but when I attempt to assert the ...
0
votes
0
answers
158
views
Using ASP.NET Core 8 Web API project : I am trying to access controller and its attributes from middleware
In my ASP.NET Core 8 Web API based project, I have a middleware which is being executed for every request. I want to avoid this situation and want it to only execute for those API controllers which ...
-2
votes
1
answer
143
views
Cannot access a disposed object in Entity Framework
I am creating a middleware to store all incoming API request and response body along with some other data, I am using Entity Framework as my ORM.
It's working well, but in some request and response ...
0
votes
0
answers
69
views
How to create middleware API in .NET Core
I need to write a middleware micro service API from another website which is SSL secured; I need to load the certificate and wait for any post calls on that url and catch the data in my end. I have ...
0
votes
1
answer
694
views
Access denied when adding rule to Windows firewall (INetFwPolicy2) with C# from Core Middleware program
I'm trying to add a rule to Windows firewall in .Net Core Middleware (httpHandler) written in C# . The code looks like this:
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type....
2
votes
1
answer
691
views
Modifying `Request.Path` via middleware in an ASP.NET Core Web API project does not change the controller/action used
I have a small sandbox application based on the ASP.NET Core Web API template where I am attempting to modify the controller/action to be used based on a custom header and to facilitate this I am ...
-1
votes
1
answer
1k
views
Why a middleware does not get executed if applied after app.UseEndpoints() in ASP.NET Core Web APIs
I am trying to create a middleware that should execute after the execution of endpoint. But when I add middleware in after the app.UseEndPoints(), it never gets invoked, however it is invoked if ...
0
votes
0
answers
232
views
C# Asp.Net Core Middleware - Page Loading Time
I have implemented a middleware class that determines the elapsed time that a page took to load.
public sealed class PageLoadTimeMiddleware
{
private readonly RequestDelegate _next;
...
0
votes
1
answer
188
views
Create Ocelot middleware in c#
Net core. I am trying to implement Authorization in Ocelot gateway but due to some oprn issues at ocelot side i am looking at alternatives mentioned at https://github.com/ThreeMammals/Ocelot/issues/...
0
votes
0
answers
95
views
ASP.NET Core Middleware - redirect happens before code for changing headers is executed
I have written a middleware that supposed to cache a specific endpoint redirect (302) and add parameters to it's query string.
This is my middleware code:
public class ...
0
votes
1
answer
1k
views
Redirect to login from .NET Core auth middleware
I have an ASP.NET Core 8 MVC app, and I'm using auth middleware to authenticate and ensure that an access token (JWT) resides in the cookies.
Working to make sure that when an action with an [...
0
votes
2
answers
193
views
Inline middleware doesn't work in Asp.Net WebApi template project
I created a new Asp.Net WebApi project just to experiment, and I added a new inline middleware as in the documentation. The application starts, but when calling the action from Swagger I get a result ...
1
vote
1
answer
910
views
Prometheus not Scraping Custom Metrics (prometheus_demo_request_total) from ASP.NET Core Application with OpenTelemetry
I have implemented a custom middleware in my ASP.NET Core application to log HTTP request metrics using Prometheus. I implemented the middleware using the link. However, despite the middleware being ...
0
votes
0
answers
299
views
Matching and Rebuilding URL Routes in ASP.NET Core
I'm working on an ASP.NET Core application where I have a default route template,
for example: ~/api/{area}/[controller]/{action?}/{id?}.
My goal is to match incoming URLs with other route templates ...
0
votes
2
answers
183
views
Returning multiple implementations of same interface from Abstract Factory with ASP.NET Core
I want to make multiple implementations of a specific interface accessible through an Abstract Factory in .NET Core. Based on a supplied enum the correct implementation should be returned. This is my ...
0
votes
1
answer
166
views
Show 404 status and page-not-found View without actually redirecting to pagenotfound Nopcommerce 4.5
Using Nopcommerce V.4.5
Whenever there is a 404 error it redirect to /pagenotfound.
I am trying for it to show the same View on the original URL that was 404.
So far:
I have added a custom middleware ...
0
votes
1
answer
109
views
RequestDelegate as discard parameter in custom middleware class
I saw the following code:
class ReaderMiddleware
{
IReader reader;
public ReaderMiddleware(RequestDelegate _, IReader reader) => this.reader = reader;
public async Task ...
3
votes
1
answer
471
views
ASP.NET C# WebApp passing named parameters to custom middleware using app.UseMiddleware
C# aspnet webapp, I have the following constructor in my middleware:
public MiddlewareCustomRuntimeExceptionHandler (RequestDelegate next, ILogger<MiddlewareCustomRuntimeExceptionHandler> ...
0
votes
0
answers
55
views
An .NET API; how to respond to large multi-form request without closing connection?
Consider this client request:
var content = new MultipartFormDataContent();
var stream = new FileStream("c:\10GB.zip", FileMode.Open, FileAccess.Read);
content.Add(new StreamContent(stream), ...
1
vote
1
answer
1k
views
ASP.NET Core - Can UseSession() be used before UseAuthentication() and UseAuthorization()?
I'm working on an ASP.NET code base that uses sessions, authentication, and authorization.
They are initialized in the following order:
app.UseSession();
app.UseAuthentication();
app.UseAuthorization()...
0
votes
0
answers
165
views
Middleware Or Filter
I have a scenario where I want to check a feature flag per request. The way I have implemented this so far is I use middleware..
public class SalesFeatureMiddleware
{
private readonly ...
0
votes
1
answer
322
views
ASP.NET Core: Cancelled tasks get stuck in IIS Worker Process, causing application to be un-responsive to the users
At the time of high user traffic, the server struggles to keep up with the user requests, which causes the users to refresh the page one or more time. This causes the cancelled tasks to pile up in the ...
0
votes
1
answer
1k
views
Why is my ASP.NET Core middleware pipeline short-circuit code returning an empty response?
I have an ASP.NET Core web application in which I have a pipeline of several custom middleware functions. I'm trying to add a new one to the beginning of the pipeline that short-circuits the rest of ...
3
votes
3
answers
3k
views
Error when modifying response headers in middleware
I'm trying to modify the response headers in some middleware after it has finished in the controller, but I'm getting an error message:
System.InvalidOperationException: Headers are read-only, ...
0
votes
1
answer
758
views
Is there a way to stop middleware propagation in OnAuthenticationFailed event in ASP.NET Core?
I use the event OnAuthenticationFailed in JWTBearer only to handle the response when the token expires.
Here's the code:
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = ...
0
votes
1
answer
771
views
How to run a middleware first in a pipeline but with endpoint metadata?
I need to filter some of our API actions to work only from local host. Seems there are a few methods to accomplish this:
setup CORS;
Add an Authorization filter or an Action filter;
Add a middleware ...
1
vote
1
answer
103
views
strange behaviour with exception handling
i have a dotnet core 6 api with a very strange behaviour in exception handling
there's an exception middleware that should handle all exception in api calls (which is correctly instantiated in app ...
1
vote
1
answer
429
views
Using different loggers or logging configurations in .NET 7 API
I have a React app that uses a .NET 7 API. We are using Graylog for logging. The idea is to provide an API endpoint for the react app to POST its error logs. I want to use a different log source if ...
0
votes
1
answer
554
views
Handle outbound proxy in .net core
I am migrating the asp.net web application to asp.net core 6.0. For handling inbound proxies i have followed the following Microsoft link;
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/...
0
votes
1
answer
545
views
Rewriting ASP.NET Core response duplicates the content instead of replacing the original stream
I have an ASP.NET Core application with a custom middleware designed to replace some external CDN links. The middleware correctly updates the response body with the new data, but keeps appending it to ...
0
votes
1
answer
2k
views
Statements after await next(context) is not executed in ASP.NET Core middleware
I have created a custom middleware and added a statements before and after the await next(context) method call.
If there is no middleware after my custom middleware, then the statements after next(...
0
votes
1
answer
795
views
How can I set a default header for all the HTTP requests using DelegatingHandler middlewhare?
I use a middleware for an HttpClient. I use one instance of HttpClient as a singleton (we don't use DI, otherwise an HttpClientFactory would be a better option).
My question:
Is it possible to set a ...
0
votes
0
answers
315
views
ASP.NET Core failed requests is getting executed multiple times
I have an ASP.NET Core 6.0 Web API. One of the middleware catches an exception and translates it to a user-friendly error message as response.
This is existing web API and multiple middleware are ...
0
votes
1
answer
487
views
How to fix the problems in my global error handling page?
I am working on an ASP.NET Core 6 MVC project and trying to implement global error handling for web pages.
Currently, the code is local on my laptop with Windows 11, Visual Studio 2022 and using ...
0
votes
1
answer
112
views
ASP.NET Core - Middleware Reordering in Startup class
I have used two Map methods one after other in Startup class in a demo ASP.NET Core 5.0 Empty project. I know that Map method is used to branch the middleware pipeline. As per the pathMatch string, ...