Summary:
I am using Hangfire to handle running background jobs at set intervals, like checking for expired Widgets nightly. I want to know the best way to hit an ASP.NET Web Api 2 endpoint (Likely just GET and POST) from a job that is running.
Versions of stuff (if this matters)
- .NET 4.5 MVC 5
- Web Api 2(.1?)
- Hosting sites Windows azure
- 8GB of RAM see footnote (1)
- local dev using IIS express (or whatever the builtin one is in VS2013)
My specific questions
- Is this implementation the proper way to open/close a connection to my api from something like a background task?
- In the code below, how can I dynamically get the client.BaseAddress string (http://whatever.xxx)? It would be incredibly handy to be able to do some like what I have in the second psuedo-code snippet.
Here is the code I got from this blog post
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:43736/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/do/someshiz/");
if (!response.IsSuccessStatusCode)
{
//todo: stuff
}
}
This is pretty clean already I suppose but I am woefully inexperienced with using the HttpClient class and most of my api interactions are from javascript.
What I want to do for getting the HttpClient.BaseAddress string
if(IAmRunningThisOnMyLocalMachine) {
baseAddress = "http://localhost:1337/"
} else {
//I Already have a way to determine if I am on the staging server or live site
if(IsStagingServer){
// staging server base address
baseAddress = "http://staging.whatever.com/"
} else {
// live base address
baseAddress = "http://whatever.com/"
}
}
For the root else branch it is less of a big deal, those strings are more or less constant. When I am running locally though I want it to work regardless of if I am localhost:AnyPort or any other variations of IIS Express.
1: Just kidding about the RAM, just wanted to see if I could make the read whisper 'wtf' out loud. Please advise if successful