title: Asp.net core middleware to run logic based on request url
body: <p>I have an .net core application that works as api gateway and authentication service at the same time. The authentication controller looks like this:</p>
  
  <pre><code>[AllowAnonymous]
      [HttpPost, Route("request")]
      public IActionResult RequestToken([FromBody] TokenRequest request)
      {
  
          string token = "";
          if (!ModelState.IsValid)
          {
              return BadRequest(ModelState);
          }
  
  
          if (_authService.IsAuthenticated(request, out token))
          {
              return Ok(token);
          }
  
          return BadRequest("Invalid Request");
      }
  </code></pre>
  
  <p>Is there a way to crate a middleware that can distinguish the request url so I can redirect it to the controller when it is smth like "/auth" and "OTHERS". The "OTHERS" should be redirected to a service, which works running the following in Configure method:</p>
  
  <pre><code>app.Run(async (context) =&gt;
              {
                  using (var serviceScope = app.ApplicationServices.CreateScope())
                  {
                      var routing = serviceScope.ServiceProvider.GetService&lt;IRoutingService&gt;();
  
                      var content = await routing.RouteRequest(context.Request);
                      await context.Response.WriteAsync(await content.Content.ReadAsStringAsync());
                      content.Dispose();
  
                      // Seed the database.
                  }
              });
  </code></pre>