Tuesday, 15 September 2009

Checking MIME type for cross domain Silverlight hosting

I recently ran into some problems trying to embed a Silverlight application in a web page hosted on another server. It seems that to do so, you must have your MIME type for .xap files correctly configured (should be application/x-silverlight-app). Interestingly, this is not required if you are hosting the .xap file in a web page on the same domain.

Unfortunately for me, my shared Linux hosting provider allows no way of configuring or even viewing the MIME types. After searching in vain for a utility that would let me have a look and see what MIME type a given URL was returning, I wrote my own test function. It turns out to be possible in just two lines of code – create a WebRequest, and examine the ContentType of the WebResponse.

[TestFixture]
public class MimeTypeChecker
{
    [Test]
    public void CheckSilverlightMimeTypeIsCorrect()
    {
        string mimeType = GetMimeType("http://www.mydomain.com/mysilverlightapp.xap");
        Assert.AreEqual("application/x-silverlight-app", mimeType);
    }

    public string GetMimeType(string url)
    {
        WebRequest request = WebRequest.Create(url);
        WebResponse response = request.GetResponse();
        return response.ContentType;
    }
}

Update: If your .xap file is hosted on an Apache server on Linux, you can set up the MIME types correctly by creating a .htaccess file. This can be put in the root of your hosting space, or just in the folder containing the .xap file. It only needs the .xap registration, but the example I show below configures xaml and xbap as well:

AddType application/x-silverlight-app .xap
AddType application/xaml+xml .xaml
AddType application/x-ms-xbap .xbap

No comments: