title: "No such host is known" when publishing locally, but not when debugging in Visual Studio
body: <p>Related: <a href="https://stackoverflow.com/questions/56852702/no-such-host-is-known-system-net-http-httprequestexception">No such host is known —&gt; System.Net.Http.HttpRequestException:</a></p>
  
  <p>So, I have an odd problem: whenever I perform any call to a RESTful API using <code>HttpClient</code>, I get a the following error: <code>System.Net.Http.HttpRequestException: No such host is known</code></p>
  
  <p>I've seen several other Q&amp;As that discuss this, but many of these (such as the one I link to) discuss it specifically in the context of an Azure VM. Many of them suggest that this is caused by a DNS issue.</p>
  
  <p>My situation is a little different the other Q&amp;As I've read, though: when I run my web site by debugging in Visual Studio 2019, it runs just fine. However, when I publish to IIS locally, I get this exception whenever I try to do a call to <code>HttpClient</code>.</p>
  
  <p>Also, unlike some of the other articles I've read about this, this does not happen intermittently for me - it happens every single time I try to do an API call.</p>
  
  <p>If this is caused by a DNS issue like some of the other Q&amp;As suggest, that suggests that there must be some difference between when I publish locally and when I debug in Visual Studio.</p>
  
  <p>Here's how I configure my Publish (summary of the image below for those who prefer text):
  <a href="https://i.stack.imgur.com/Mbse0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mbse0.png" alt="enter image description here"></a></p>
  
  <p>Image summary:</p>
  
  <ul>
  <li>Web Deploy with WebPublishMethod MSDeploy</li>
  <li>TargetFramework netcoreapp3.1</li>
  <li>LastUsedBuildConfiguration Release</li>
  <li>LastUsedPlatform x86</li>
  <li>SelfContained false</li>
  <li>MSDeployPublishMethod InProc</li>
  <li>MSDeployServiceURL localhost</li>
  </ul>
  
  <p>Additional details:
  - Destination URL <a href="http://localhost:80" rel="nofollow noreferrer">http://localhost:80</a>
  - IIS Application Pool is set to "No managed code", as is usually suggested</p>
  
  <p>Also, this occurs regardless of how I create the <code>HttpClient</code> instance and the code works just fine when debugging, so I think that this is more likely to be a configuration issue than a code issue, but for what it's worth, I use the following code in my <code>Startup</code> class to create it. (See also <a href="https://codereview.stackexchange.com/questions/240699/asp-net-core-3-1-addhttpclient-call-that-includes-a-call-to-the-database">here</a> for reference).</p>
  
  <pre><code>       services.AddHttpClient("MyNamedClient", (sp, c) =&gt;
          {
              c.BaseAddress = new Uri("https://api.smartrecruiters.com/");
  
              c.Timeout = new TimeSpan(4, 0, 0);
  
              c.DefaultRequestHeaders.Accept.Clear();
  
              c.DefaultRequestHeaders.Add("Accept", "application/json");
  
              var ctx = sp.GetService&lt;DatabaseContext&gt;();
  
              Security security = ctx.Security.First();
  
              c.DefaultRequestHeaders.Add("APIToken", security.Apikey);
          });
  </code></pre>
  
  <p>I then use ASP.NET Core's Dependency Injection to get a <code>HttpClient</code> instance whenever I need it.</p>
  
  <p>I also tried creating <code>HttpClient</code> as a singleton (which I know is <em>not</em> the recommended way of doing this in an ASP.NET Core application), but I had the same problem with that approach.</p>
  
  <p>Here's the full error details from Event Viewer from when I try to do a <code>GetAsync</code> call using <code>HttpClient</code>:</p>
  
  <pre><code>Category: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware
  EventId: 1
  RequestId: 8000000c-0006-ff00-b63f-84710c7967bb
  RequestPath: /UsersObject/GetUsersAPICall
  SpanId: |f32bc4b9-41d453941179fa9f.
  TraceId: f32bc4b9-41d453941179fa9f
  ParentId: 
  
  An unhandled exception has occurred while executing the request.
  
  Exception: 
  System.Net.Http.HttpRequestException: No such host is known.
   ---&gt; System.Net.Sockets.SocketException (11001): No such host is known.
     at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
     --- End of inner exception stack trace ---
     at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
     at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
     at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
     at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
     at [Namespace].MyHttpClient.GetAsyncWithRetries(HttpClient client, String url) in C:\Users\[Removed]\source\repos\[Removed]\MyhHttpClient.cs:line 54
     at SR_Interaction.Models.SRUser.Search(String emailAddress, HttpClient client) in C:\Users\[Removed]\Models\SRUser.cs:line 100
     at Bosch_Live_Docs.Controllers.UsersObjectController.GetUsersAPICall(String query) in C:\Users\[Removed]\Controllers\UsersObjectController.cs:line 58
     at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeActionMethodAsync&gt;g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeNextActionFilterAsync&gt;g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeInnerFilterAsync&gt;g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextResourceFilter&gt;g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeFilterPipelineAsync&gt;g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
     at Microsoft.AspNetCore.Routing.EndpointMiddleware.&lt;Invoke&gt;g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
     at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.&lt;Invoke&gt;g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
  </code></pre>
  
  <p>Anyone have any suggestions about how I might be able to fix this? I think it's probably either my IIS configuration or my publish settings - or am I on the wrong track entirely here?</p>
  
  <p><strong>Edit:</strong> As requested, here's the controller code:</p>
  
  <pre><code>    [HttpGet]
      [Authorize(Roles = "CreateUser,PatchUser")]
      public async Task&lt;IActionResult&gt; GetUsersAPICall([Bind("query")] [RegularExpression(@"^\w+(\.\w+)*@\w+(\.\w+)+|(\w+(\s\w+)*)$", ErrorMessage = "This does not look like a valid query")] string query)
      {
          if (query == null)
          {
              return BadRequest();
          }
          else if (!ModelState.IsValid)
          {
              // TODO: What to do with this? How do we actually show the validation error?
              return BadRequest("Does not look like a valid query");
          }
  
          List&lt;SRUser&gt; users = await SRUser.Search(query, clientFactory.CreateClient(Startup.srNamedClient));
  
          users = users.OrderBy(ur =&gt; ur.firstName).ToList();
  
          if (users.Any())
          {
              return PartialView("_UserList", users);
          }
          else
          {
              return NotFound();
          }
      }
  </code></pre>
  
  <p>And here's where I do the actual call:</p>
  
  <pre><code>public static async Task&lt;List&lt;SRUser&gt;&gt; Search(string emailAddress, HttpClient client)
      {
          string json;
  
          using (HttpResponseMessage msg = await client.GetAsync("user-api/v201804/users?limit=100&amp;q=" + emailAddress))
          {
              json = await msg.Content.ReadAsStringAsync();
          }
  
          return JsonSerializer.Deserialize&lt;NextPageContainer&lt;SRUser&gt;&gt;(json).content;
      }
  </code></pre>
  
  <p><strong>Further edit:</strong></p>
  
  <p>Here's the Application Pool:</p>
  
  <p><a href="https://i.stack.imgur.com/JFkcP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JFkcP.png" alt="enter image description here"></a></p>
  
  <p>Here are the modules I have installed:</p>
  
  <p><a href="https://i.stack.imgur.com/ISqm0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ISqm0.png" alt="enter image description here"></a></p>
  
  <p>I'm slightly confused about this particular one:</p>
  
  <p><a href="https://i.stack.imgur.com/7KP53.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7KP53.png" alt="enter image description here"></a></p>
  
  <p>Is it necessary to include both? When I look at the Ordered view, the "old" one is actually higher:
  <a href="https://i.stack.imgur.com/gw2ed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gw2ed.png" alt="enter image description here"></a></p>
  
  <p>However, I can't reorder it.</p>
  
  <p>Are these problems?</p>
  
  <p><strong>Even further edit:</strong> For the version that was published locally, I found that this problem occurs when my App Pool runs under a built-in account (such as ApplicationPoolIdentity). However, it's fixed when I use a specific user account. However, this does not work on the server.</p>