Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC OutputCache with POST Controller Actions

I'm fairly new to using the OutputCache attribute in ASP.NET MVC.


Static Pages

I've enabled it on static pages on my site with code such as the following:

[OutputCache(Duration = 7200, VaryByParam = "None")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        //...

If I understand correctly, I made the whole controller cache for 7200 seconds (2 hours).


Dynamic Pages

However, how does it work with dynamic pages? By dynamic, I mean where the user has to submit a form.

As an example, I have a page with an email form. Here's what that code looks like:

public class ContactController : Controller
{
    //
    // GET: /Contact/

    public ActionResult Index()
    {
        return RedirectToAction("SubmitEmail");
    }

    public ActionResult SubmitEmail()
    {
        //In view for CAPTCHA: <%= Html.GenerateCaptcha() %>
        return View();
    }

    [CaptchaValidator]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SubmitEmail(FormCollection formValues, bool captchaValid)
    {
        //Validate form fields, send email if everything's good...

            if (isError)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }

    }

    public void SendEmail(string title, string name, string email, string message)
    {
        //Send an email...

    }
}

What would happen if I applied OutputCache to the whole controller here?

Would the HTTP POST form submission work? Also, my form has a CAPTCHA; would that change anything in the equation?

In other words, what's the best way to approach caching with dynamic pages?

Thanks in advance.

like image 822
Maxim Zaslavsky Avatar asked May 30 '10 02:05

Maxim Zaslavsky


1 Answers

By taking advantage of output caching, you can dramatically improve the performance of an ASP.NET MVC application. Instead of regenerating a page each and every time the page is requested, the page can be generated once and cached in memory for multiple users.

First of the scenario you are going to implement is not proper. Keep one thing in mind the output cache should be used only at time where it does not affect your business logic, You wanted to reduce sever load & Sql data Retrieval of frequently used page but less frequently update data.

Fortunately, there is an easy solution. You can take advantage of a feature of the ASP.NET framework called post-cache substitution. Post-cache substitution enables you to substitute dynamic content in a page that has been cached in memory.

http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/adding-dynamic-content-to-a-cached-page-cs

like image 115
Kaushik Thanki Avatar answered Nov 17 '22 03:11

Kaushik Thanki