Queries count for page in asp.net mvc

2019-09-06 16:34发布

问题:

I want to calculate how much queries are executed when i request a page in asp.net mvc. Difficults in page logic: sum queries are executed in main controller action, but others - in widget controller actions, which are called by Html.ActionLink in master page.

I wrote base class for all controllers in which i'm encapsulate query called function to increase queries counter - static variable. On page loading it work nice, all queries are counted, but when i requested second page my static counter doesn't reset, what should i do?

回答1:

If possible avoid using a static variable. An instance variable on the base controller would work just as easily if all the methods shared the same controller instance. I assume that you're not instantiating new controllers to execute the other actions.

EDIT: After thinking about it, a simple static variable won't work as it will be shared across all requests. You'll need to use some sort of dictionary keyed by some unique id identifying the request. Perhaps based on a combination of the HostAddress and a timestamp created when the request is initiated. Perhaps using the application cache would work so it's available from everywhere and automatically cleaned up when you are done. This is only going to get more complicated as you consider all the possible way that multiple threads may interact. Again, I'd say trying to use an instance variable may be the best way to handle this.



回答2:

extend your MvcApplication Class (in your global.asax) with

 public static int QueryCount { get; set; }

then create a handler for the MvcApplication.BeginRequest event or extend your existing handler with

this.QueryCount = 0;

and in your BaseController Class you can increment your counter with

MvcApplication.QueryCount++;

hth



回答3:

Are you using SQL Server? If so you can use the SQL Server Profiler from the Tools menu to see how many queries are run for a specific page.