Feed Subscribe
Exception has been thrown by the target of an invocation.


WebResource.axd gives 404 or don’t use this.GetType() in RegisterClientScriptResource

by ondrejsv 19. December 2010 11:26

Since ASP.NET 2.0 we can embed resources in assemblies and use them on pages very easily with help of the magical WebResource.axd. Once we embed a resource in the assembly and mark the assembly with the appropriate WebResoruce attribute, we can call the RegisterClientScriptResource on the ClientScriptManager (instance of which is exposed through the Page.ClientScript property). The signature of the method is:

public void RegisterClientScriptResource( Type type, string resourceName )

The problem starts if your resource is embedded in the web-site assembly and you use call the registration method on directly on the page and use this.GetType() for the type parameter. The script include gets in your page but the link to WebResource.axd gives you 404 – Not found. Why?

The links to WebResource.axd are in the format ~/WebResource.asx?d=encryptedScriptId&t=timestamp

where encryptedScriptId is the name of the assembly the resource is embedded in together with its name. The assembly used to look for the resource is the same assembly in which is type defined. This is quite different from the other registration methods on the ClientScriptManager (RegisterClientScriptInclude, RegisterClientScriptBlock, …) which also take the type parameter but solely for the purpose of building a key identifying the script so that framework does not register it twice. You can find a method to decrypt the script identifier on the Hristo Deshev blog. Remember the process ASP.NET processes a web page? For each and every web page ASP.NET creates a derived class (containing processed markup) that gets compiled in a different assembly than yours, indeed. This is why you cannot use this.GetType(). Just use typeof(you page class name) and you’ll be fine.

Tags:

Comments are closed