Dynamically configure themes in ASP.NET

I have an application that has different domains connected, instead of copying and changing each application, I use the same physical location on the hard drive, but separate application pools and websites in IIS.

Basically I want to change the theme based on the host name. i.e. the user comes to "websome.com" gets the theme "websome" and the user comes to "jamessome.com" gets the theme "jamessome".

I set the theme in the "pages" attribute in web.config, which applies the theme globally to the entire website. Is there a way to change this setting on the fly based on domain usage? Perhaps this is possible, but what reduces the size and what you propose to do with a little code to simplify the solution. Since I understand that if I edit web.config every time a user comes in, it will take a lot of time, which is not so elegant ... So, any ASP.NET gurus can write two lines of code for the magic to happen?

There are several solutions to this problem on the website, but it will require me to add code to the Page_Init event of each page on the website, which is unrealistic.

+4
source share
1 answer

Actually, it must be set to Page_PreInit , it will not work if you try to change the theme in Page_Init .

The most common solution is to use a parent class for all of your pages. This is a one-time change and puts the logic in the parent class. Instead of inheriting from Page you inherit, say, ThemedPage . Inside the ThemedPage class, which naturally inherits from Page , you can override the Page.OnPreInit method.

You asked for “two lines,” this is actually one if you remove the clutter. This is VB:

 Public Class ThemedPage Inherits Page Protected Overrides Sub OnPreInit(ByVal e As System.EventArgs) Me.Theme = HttpContext.Current.Request.Url.Host.Replace(".com", "") MyBase.OnPreInit(e) End Sub End Class 

And instead:

 Partial Class _Default Inherits System.Web.UI.Page 

Now you write this:

 Partial Class _Default Inherits ThemedPage 

It's all! One-time search / replacement, and you're done. For completeness, here is the same (only class) for C #:

 // C# version using System.Web; using System.Web.UI; public class ThemedPage : Page { protected override void OnPreInit(System.EventArgs e) { this.Theme = HttpContext.Current.Request.Url.Host.Replace(".com", ""); base.OnPreInit(e); } } 

Update: added sample VB code
Update: added C # code sample

Note. the theme must exist, otherwise you will get an exception: Theme 'ThemeName' cannot be found in the application or global theme directories. . If you want to use the default theme or not, if the theme is not there, wrap it around the try / catch and use the catch to set the default theme.

+8
source

All Articles