I have an ASP.NET MVC application which is invoking a ASP.NET Web Api REST service:
public class MyClass
{
private static HttpClient client = new HttpClient();
public async Task DumpWarehouseDataIntoFile(Warehouse myData, string path, string filename) // See Warehouse class later in this post
{
try
{
//Hosted web API REST Service base url
string Baseurl = "http://XXX.XXX.XX.X:YYYY/";
//using (var client = new HttpClient()) --> I have declared client as an static variable
//{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Serialize parameter to pass to the asp web api rest service
string jsonParam = Newtonsoft.JsonConvert.SerializeObject(myData);
//Sending request to find web api REST service resource using HttpClient
var httpContent = new StringContent(jsonParam, Encoding.UTF8, "application/json");
HttpResponseMessage Res = await client.PostAsync("api/Warehouse/DumpIntoFile", httpContent);
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
// Some other sftuff here
}
//}
}
catch (Exception ex)
{
// Do some stuff here
} // End Try
} // End DumpWarehouseDataIntoFile method
} // End class
The ASP.NET Web API REST Controller:
public class WarehouseController : ApiController
{
public bool DumpIntoFile(string data)
{
// Stuff here
}
}
I have used an HttpClient static variable, I am not enclosing it within a 'using' block because of it is not recommended as explained in this link: YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE
When this code is executed it fails with the error:
System.Net.Http.HttpRequestException: An error occurred while sending the request. System.Net.WebException: The remote name could not be resolved: 'xxx'
I think I do not need to dispose HttpClient client object, right?
How can I solve this?
I am using Visual Studio 2013 and NET 4.5 (Not Core)
UPDATE 2020/12/10: Previous error was occurring because of ASP.NET Web API REST Url was not configured correctly in the internal DNS.
Now after solving previous error I get below one:
404 Not Found
Below some messages of the error returned by client.PostAsync:
Ping to ASP.NET Web API Rest is working.
Maybe it is something missing in my web api routes configuration under App_Start\WebApiConfig.cs below?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Configuración y servicios de API web
// Rutas de API web
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

Taskand await it to finish?