title: Redirect outside of the Controllers context in ASP.NET Core
body: <p>I do not know if this is actually possible, but I think it' s worth a try to find out.</p>
  
  <p>There are maybe other and better patterns (if you know one let me know, I will look them up) to do this, but I'm just curious to know if this is possible.</p>
  
  <p>When you have to call an API you could do it directly from within the controller using the <code>HttpClient</code> like this:</p>
  
  <pre><code>    [Authorize]
      public async Task&lt;IActionResult&gt; Private()
      {
          //Example: get some access token to use in api call
          var accessToken = await HttpContext.GetTokenAsync("access_token");
  
          //Example: do an API call direcly using a static HttpClient wrapt in a service
          var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com/api/some/endpoint");
          request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
          var response = await _client.Client.SendAsync(request);
  
          if (response.StatusCode == HttpStatusCode.Unauthorized)
          {
              //Handle situation where user is not authenticated
              var rederectUrl = "/account/login?returnUrl="+Request.Path;
              return Redirect(rederectUrl);
          }
  
          if (response.StatusCode == HttpStatusCode.Forbidden)
          {
              //Handle situation where user is not authorized
              return null;
          }
  
          var text = await response.Content.ReadAsStringAsync();
  
          Result result = JObject.Parse(text).ToObject&lt;Result&gt;();
  
          return View(result);
      }
  </code></pre>
  
  <p>When you would do this you'll have to reuse some code over and over again.  You could just make a Repository but for some scenarios that would be overkill and you just want to make some quick and dirty API calls. </p>
  
  <p>Now what I want to know is, when we move the logic of setting an Authorization header or handling the 401 and 403 responses outside the controller, how do you redirect or control the controller's action.</p>
  
  <p>Lets say I create a Middleware for the HttpClient like this:</p>
  
  <pre><code>public class ResourceGatewayMessageHandler : HttpClientHandler
  {
      private readonly IHttpContextAccessor _contextAccessor;
  
      public ResourceGatewayMessageHandler(IHttpContextAccessor context)
      {
          _contextAccessor = context;
      }
  
      protected override async Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
      {
          //Retrieve acces token from token store
          var accessToken = await _contextAccessor.HttpContext.GetTokenAsync("access_token");
  
          //Add token to request
          request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
  
          //Execute request
          var response = await base.SendAsync(request, cancellationToken);
  
          //When 401 user is probably not logged in any more -&gt; redirect to login screen
          if (response.StatusCode == HttpStatusCode.Unauthorized)
          {
              //Handle situation where user is not authenticated
              var context = _contextAccessor.HttpContext;
              var rederectUrl = "/account/login?returnUrl="+context.Request.Path;
              context.Response.Redirect(rederectUrl); //not working
          }
  
          //When 403 user probably does not have authorization to use endpoint
          if (response.StatusCode == HttpStatusCode.Forbidden)
          {
              //Handle situation where user is not authorized
          }
  
          return response;
      }
  
  }
  </code></pre>
  
  <p>We can just do the request like this:</p>
  
  <pre><code>    [Authorize]
      public async Task&lt;IActionResult&gt; Private()
      {
          //Example: do an API call direcly using a static HttpClient initiated with Middleware wrapt in a service
          var response = await _client.Client.GetAsync("https://example.com/api/some/endpoint");
  
          var text = await response.Content.ReadAsStringAsync();
  
          Result result = JObject.Parse(text).ToObject&lt;Result&gt;();
  
          return View(result);
      }
  </code></pre>
  
  <p>The problem here is that <code>context.Response.Redirect(rederectUrl);</code> does not work. It does not break off the flow to redirect. Is it possible to implement this, and how would you solve this?</p>