2

I've implemented Web API 2 with a Kentico 9 CMS platform (generally following Kentico's documentation) and on the whole it's working well. However, in my controllers I'm finding SiteContext.CurrentSite always returns null. Is this expected behaviour or am I doing something wrong?

Not sure if it makes a difference but the platform hosts multiple sites under a single domain as per this documentation. So my sites are running at the following URLs...

  • domain.com/site1
  • domain.com/site2
  • etc.

...and the API is available under the following paths...

  • domain.com/site1/customapi
  • domain.com/site2/customapi
  • etc.

Currently I'm having to use the Request object to pull out the request path and check this against the sites from Kentico's SiteProvider to find which Kentico site the current request relates to, but I wouldn't have though that necessary since the API is running as part of the site.

Is there something I can do to wire this up properly? FYI I've noticed that LocalizationContext.CurrentCulture does return a CultureInfo object so it's not as though I'm completely disconnected from Kentico's context...

UPDATE WITH SOLUTION

Thanks to @martin-makarsky for the answer below. Used this to create the following extension method which can be called from controller using Request.GetCurrentSite()

public static SiteInfo GetCurrentSite(this HttpRequestMessage request)
{
    return SiteInfoProvider.GetRunningSiteInfo(request.RequestUri.Host, System.Web.HttpRuntime.AppDomainAppPath);
}
Tom Troughton
  • 3,941
  • 2
  • 37
  • 77

1 Answers1

5

Well, nobody answered this question so I`ll give it a try. SiteContext uses internally HttpContext.Current which is little bit 'unreliable' in web api due to some thread and async related stuff (does your action contain await?). This could explain your nulls when calling SiteContext.CurrentSite in your controller.

So back to your problem - you need to get current SiteInfo inside you app (probably web api controller or service or repository) - this means you likely know your current domain or appPath. I would try to use something from SiteInfoProvider like GetRunningSiteInfo(string domainName, string applicationPath) to get current SiteInfo.

Good luck!

Community
  • 1
  • 1
Martin Makarsky
  • 2,580
  • 1
  • 17
  • 28
  • Funny enough, I just came across this question when faced with the same problem again! Sorry I didn't mark as the answer before. You're spot on, this is the correct answer. See my edit above for an extension method which uses this approach. – Tom Troughton Nov 16 '17 at 15:13