I need a solution that lets me accomplish the following:
- Returning CSS that is dynamically generated by an action method
- Choosing CSS file depending on request parameter or cookie
- Using a tool to combine and compress (开发者_如何学运维minify) CSS
I am currently considering why there is no CssResult in ASP.NET MVC, and whether there might be a reason for its absence. Would creating a custom ActionResult not be the best way to go about this? Is there some other way that I've overlooked to do what I need?
Any other suggestions or hints that might be relevant before I embark on this task will also be appreciated :)
You need to return a FileResult
or ContentResult
with a content type of text/css
.
For example:
return Content(cssText, "text/css");
return File(cssStream, "text/css");
EDIT: You can make a Css
helper method in your controller:
protected ContentResult Css(string cssText) { return Content(cssText, "text/css"); }
protected FileResult Css(Stream cssStream) { return File(cssStream, "text/css"); }
No need to create a custom ActionResult type. Since CSS a "just text", you should be fine using ContentResult
. Assuming you inherited the Controller
class, simply do:
return Content(cssData, "text/css");
I am currently considering why there is no CssResult in ASP.NET MVC, and whether there might be a reason for its absence.
Simply because the team had its hands full and obviously it's some effort to add ActionResults for all cases in life.
Would creating a custom ActionResult not be the best way to go about this?
It would be a correct way to do so. I added RssActionResult and AtomActionResult for my needs. It's also reasonable to add more types, for docs, pdfs, images etc.
Returning CSS that is dynamically generated by an action method
Also keep in mind that a browser would normally cache the css unless it sees some variation in the url. Adding an always incrementing parameter is a usual solution.
<link rel="stylesheet" href="http://site.com/styles.css?v=26">
An extra route parameter for version would probably work as well.
精彩评论