CSS file only loads in IE when fetched via an ASP.NET MVC Controler + Action
I'm serving up a site's CSS content via an ASP.NET MVC's Controller + Action. The css "file" appears to deliver correctly down the wire but only IE will apply it. 开发者_StackOverflow社区Other browsers (Firefox, Opera, Chrome) ignore the CSS file and render the page without styling. IE8 works perfectly.
This is the essential code that I'm using to return the CSS via the controller and action:
public void CSS(string version)
{
string cssFile = Server.MapPath("/site.css");
string cssContents = System.IO.File.ReadAllText(cssFile);
Response.Write(cssContents);
}
Note that the version can be any string. I have tried with strings such as "myversion.css", "1.css", "1234", "arbitrary" etc.
The all work in IE8 but not in any other browser. Any ideas?
You'll have to send the proper Content-type: text/css
header.
Firefox will ignore the style sheet otherwise, and output a warning in its error console. Same goes probably for the other Gecko/Webkit based browsers.
This was one of those cases where after typing out the question and pondering how to phrase it and then posting it the answer dawned on me. When I returned here Pekka had correctly answered the question. If anybody's interested here's some code that fixes the problem:
string fileLocation = Request.PhysicalApplicationPath + @"site.css";
ContentResult fcr = new ContentResult();
fcr.Content = System.IO.File.ReadAllText(fileLocation);
fcr.ContentType = "text/css";
return fcr;
精彩评论