5

In my ASP.NET MVC website people can choose between different css styles. In the future the name of these css styles will be stored in a database.

I have the following method (does not yet communicate with a database):

public FileResult CssStyle()
{
    string style = "/Content/wide-site.css";

    if (!String.IsNullOrWhiteSpace(style))
    {
        return File(style, "text/css");
    }

    return File("/Content/site.css", "text/css");
}

And in my _Layout.cshtml I use this line to load the stylesheet:

<link href="@Url.Action("CssStyle", "Home")" rel="stylesheet" type="text/css" />

Suppose that this CssStyle() method does a request to the database and for every page load it executes a query. What's the best way to prevent these unnecessary requests? A session perhaps?

4

3 回答 3

3

Run the query when it matters, so for example on login, and then store the CSS file name in Session. You would also need to refresh the Session variable if you have a profile page where the users can change their style - that way when they change it they would see the new style immediately.

Then in your method, pull that value out of Session:

var cssFile = Session["UserStyle"];

for example.

于 2013-03-20T14:19:33.353 回答
0

I would suggest that you either cache it or store it in a session variable.

That way you are not needlessly going off to the database everytime.

于 2013-03-20T14:19:06.787 回答
-1

First, have you confirmed that this operation needs to be optimized? If you're using sessions then you're usually accessing the file system, which is the same order of magnitude, at least on local installations, as DB accesses.

Will assume the DB is remote and over a very slow connection such that it is worth the effort to reduce DB accesses.

Also, it isn't clear how the user selects the stylesheet so assuming there will be a parameter of some sort.

If you want a solution not using sessions, say at most one DB access per CSS file per day, you could do something like this:

public FileResult CssStyle(variant which)
{
    // Hash the function, date and which stylesheet to ensure global,
    // valid, unique, and easily replicated filename
    filename = md5("get_css_style" + today() + which) + ".css"
    if (!file_exists(filename))
    {
        // DB operation here
        // create file here using filename
    }
    return File(filename, "text/css");
}
于 2013-03-20T14:39:49.713 回答