1

I have a simple ASP.NET MVC 5 (not .NET Core) project in which I want to create a simple middleware like we do in .NET Core:

   public class CustomMiddleware
   {
        internal const string HeaderKey = "RelationId";

        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            this._next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var id = Guid.NewGuid();

            if (context.Request != null)
            {
                context.Request.Headers.Add(HeaderKey, id.ToString());
            }

            await this._next.Invoke(context);
        }
  }

and in the startup we can do app.UseMiddleWare<CustomMiddleware>();

Can we do the same in an ASP.NET MVC 5 project?

Ask
  • 3,076
  • 6
  • 30
  • 63
  • I would suggest reading about custom attributes that can be run before and after processing a request. They are used in ASP.NET MVC 5 framework – Inder Preet Jun 07 '21 at 10:44
  • I was also thinking of same. But we can't use RequestDelegate in mvc project. Do you have any idea how can I achieve the same (as pasted above) if I go with custom attribute? – Ask Jun 07 '21 at 10:48

1 Answers1

0

So, instead of relying on middleware. I just created an ActionFilter that does the same:

public class CustomFilter : ActionFilterAttribute
{
        internal const string HeaderKey = "RelationId";
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var relationId = Guid.NewGuid();
            if (actionContext.HttpContext.Request != null)
            {
                actionContext.HttpContext.Request.Headers.Add(HeaderKey, relationId.ToString());
            }
        }
}
Ask
  • 3,076
  • 6
  • 30
  • 63