0

I am using the following code to get data from my api:

using (var client = new HttpClient())
{
    try
    {
        string url = "http://localhost:58639/api/cars/" + carId + "?includeOwners=true";

        var model = client
            .GetAsync(url)
            .Result
            .Content.ReadAsAsync<Car[]>().Result;
        Car c = model[0];
        newCount = c.Persons.Count;

        /* More Code */
    }
}

using this route in WebApiConfig:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Is there a way to create the URL dynamically such that if the site was hosted somewhere other than localhost this would still work? I have attempted to do this with Url.RouteUrl and UrlHelper, yet I can't find a way to include the "?includeOwners=true" filter with them.

Scott
  • 457
  • 2
  • 7
  • 22
  • Do you need something like: `Url.Content("~/api/cars/")`? – keiv.fly Jun 11 '14 at 16:20
  • Apparently my Url doesn't have a Content() method... What library are you getting Url from? – Scott Jun 11 '14 at 16:24
  • It is written that way in Razor. Probably you can write UrlHelper.Content? http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content(v=vs.118).aspx – keiv.fly Jun 11 '14 at 16:29
  • In what context does this code run, is it an ASP.NET MVC controller or WebForms page? In that case see [What's the best method in ASP.NET to obtain the current domain?](http://stackoverflow.com/questions/61817/whats-the-best-method-in-asp-net-to-obtain-the-current-domain). – CodeCaster Jun 11 '14 at 18:54
  • This code is in a SignalR hub method – Scott Jun 11 '14 at 19:07

2 Answers2

0

One way is to put the server part in a config file (web.config etc) and read it from there when you're constructing the url.

Just add the base url part in an appSetting and read it using ConfigurationManager.AppSettings["NameOfKey"]

TGH
  • 38,769
  • 12
  • 102
  • 135
-2

Please try the below code:

string domainName = ((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.ServerVariables["HTTP_HOST"];

you can dynamically load the Host and Port or the whole domainname.

MustangManiac
  • 317
  • 2
  • 13