Home > ASP.NET MVC, CSharp, Performance Optimization > ASP.NET MVC Custom Compression Action Filter

ASP.NET MVC Custom Compression Action Filter

Action filters are a powerful mechanism in ASP.NET MVC to add an additional layer of control to your action methods by attaching to the request-response pipeline. Just by decorating an action method or controller class you can perform a custom authorization based on specific rights and roles, cache and/or compress the response, localization, etc.


In order to implement a custom action filter you need to inherit from ActionFilterAttribute – this is an abstract class that has four methods that you can override:

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted

As their names imply a custom logic can be performed before/after an action method is executed and before/after the result is executed. Action filters have an Order property which specifies the order in which the filter is applied when multiple filters are used to decorate an action method.

Performance Optimizations

Nowadays with broadband internet a lot of people do not care about the performance of their web sites but they are wrong. Every single byte counts when you want to stand out – the end users do not care about what technology is powering up your system, they do care about performance. One of the first things that you could do to reduce the payload of your site is to do gzip or deflate compression – it will reduce the size of the server response by 60-65%. Compression is only applicable if the end user’s browser supports it – all major browsers support it so you do not need to worry. Gzip is more widely accepted and performs better than deflate, hence it should be your first choice.

Note: Do not apply compression to images and PDF files – they are already compressed and you will only waste CPU time to do so.

Compression Filter

Here is the code for the compression filter:

public class CompressionAttribute : ActionFilterAttribute
    public override void OnActionExecuting(ActionExecutingContext filterContext)

        HttpRequestBase request = filterContext.HttpContext.Request;
        string acceptEncoding = request.Headers["Accept-Encoding"].ToLowerInvariant();
        if (string.IsNullOrEmpty(acceptEncoding))

        HttpResponseBase response = filterContext.HttpContext.Response;
        if (acceptEncoding.Contains("gzip"))
            response.AppendHeader("Content-Encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        else if (acceptEncoding.Contains("deflate"))
            response.AppendHeader("Content-Encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);

The Accept-Encoding header of the request shows whether the browser supports compression – if it is empty the CompressionAttribute class returns and does nothing. If the value is gzip or deflate the HttpResponseBase class’s property Filter which is of type Stream is wrapped by GZipStream or DeflateStream respectively. A Content-Encoding response header is set to the value of the compression method that is used so that the browser will know how to decompress the response.

Here is a sample usage of the Compression filter:

public ActionResult Index()
    return View();


Custom action filters give some extra power in the hands of developers to perform additional tasks along the ASP.NET MVC pipeline. You saw how simple it is to write a custom action filter that is applicable to real world scenarios. This is one of the performance optimization techniques that you could apply to improve the overall performance of your site.

  1. December 7, 2009 at 11:00 pm

    Hi, great article!

    Anyone curious how to write an attribute which redirects? I.e. doesn’t allow the action it is applied on to be executed.

    Here is how: http://codepaste.net/ef5df8

  2. September 24, 2011 at 1:44 am

    This site is crazy 🙂 Cp

  3. July 12, 2014 at 9:23 am

    I’ll send you a text

  4. July 12, 2014 at 9:23 am

    I’ll send you a text

  5. October 3, 2014 at 8:12 pm

    History 10mg amitriptyline for ibs When Tyreese speculated that whoever dissected the rat was the same person that killed Karen and David, Rick started to tell him about Carol, but they were interrupted by The Governor attacking. It’s probably no coincidence that there was a series of events that prevented Rick and Daryl from ever telling Tyreese about Carol.

  6. October 3, 2014 at 8:13 pm

    Looking for work purchase avapro It is a project that has all the hallmarks of a disaster in the making. Before yesterday’s tussle in Parliament, reports had made it clear that the Army was recruiting barely half the number of reservists required to meet the target the Government had set it – yet another example of the immense difficulties the Ministry of Defence is encountering, as it presses ahead with its ill-considered plan for the most ambitious overhaul of the military for more than a generation.

  7. October 4, 2014 at 1:24 am

    I work here cheap benicar U.S. antitrust authorities will likely take a detailed look at the planned sale of a steel rolling mill in Calvert, Ala. to a consortium comprising the world’s two largest steelmakers, said the chief executive of ThyssenKrupp AG on Saturday.

  8. October 4, 2014 at 1:25 am

    I’m afraid that number’s ex-directory celexa for depression Doctors at Akron Children’s Hospital believe Sarah’s leukemia is treatable but says she will die without chemotherapy. The hospital went to court after the family decided to stop chemotherapy and treat Sarah with natural medicines, such as herbs and vitamins.

  9. October 4, 2014 at 1:25 am

    Looking for work celexa rxlist Now it's so accepted that you have different Doctors. Obviously he'll get the reverse flak that I got, to an extent, in that he's much older than the younger viewers are used to, and I was the youngest.

  10. October 4, 2014 at 1:25 am

    Are you a student? buspar-price comparison Without a title since 2004 Arsenal’s credentials are about to be examined with Chelsea next up following City. “Sometimes it is difficult to talk about [the character] of a team that you don’t know very well. Maybe they think that way about us as well. But I know they will have some difficult games and of course I hope they lose some of them. I don’t know if they have been properly tested yet but we certainly have,” says Fernandinho.

  11. October 4, 2014 at 1:26 am

    How many are there in a book? no prescription buspar Juan Eibenschutz, director general of the National Commission of Nuclear Safety and Safeguards, said it could take at least two days to safely get the material into a secure container and transport it to a waste site.

  12. October 4, 2014 at 6:28 am

    Where do you live? order ciprofloxacin online It should also be said that power training is not for the beginner. The multiple joint exercises recommended require considerable muscular strength and training experience. Adherence to the correct technique is absolutely essential.

  13. October 4, 2014 at 6:28 am

    I’m a partner in duloxetine mg The premise of the smartwatch is that it will let you perform actions you’d normally do on your cellphone, but more quickly and discreetly. The thing is the Toq isn’t really that discreet, and it’s certainly not that much more convenient than whipping out your smartphone. It may be helpful to be able to check your calendar at a quick glance, or see who you got a text message or email from after feeling a light vibration on your wrist, but that’s not a transformative experience. Instead of freeing you from obsessive smartphone checking, letting you be more immersed in the real world rather than the virtual, you end up just feeling even more dependently tied to your smartphone. That is, if you even find a need to wear or check your smartwatch in the first place.

  14. October 4, 2014 at 6:29 am

    We used to work together clomid tablets for men Foreign Affairs carefully reviews all export of weapons to ensure they “do not contribute to national or regional conflicts or instability” or “are not used to commit human rights violations,” the statement said.

  15. October 4, 2014 at 6:29 am

    I’d like to send this letter by duloxetine prices Not until the hearing was nearly over did a lawmaker address the issue head on. Rep. Ralph M. Hall (R-Tex.), the chairman emeritus of the committee, asked the panel: “Do you think there’s life out there, and are they studying us? And what do they think about New York City?”

  16. October 4, 2014 at 11:22 am

    Get a job buy amitriptyline canada The captain, Sam Warburton, is also on the bench, more often than not Hook’s starting place since that loss in Auckland. “You ask any player and they will tell you they want to be in that starting team all of the time,” said Hook. “You do get frustrated at times, but you have to keep your head and keep working.

  17. October 4, 2014 at 4:16 pm

    One moment, please buy cheap permethrin There had been the slim possibility that coach Darren Lehmann might rest the injury-prone Ryan Harris on a pitch that has been a batsman's paradise in the past month, but Harris insists he will play on.

  18. October 4, 2014 at 4:17 pm

    A financial advisor where can i buy elimite What Cerulli’s research revealed is that even though the courts are not the ideal prevention tool against domestic violence, providing on-the-spot mental-health services to victims could help prevent intergenerational cycles of violence.

  19. October 4, 2014 at 9:25 pm

    Best Site good looking tamsulosin mr Once famed for securing draws or victories with late fightbacks, United have had none under Moyes and, more worryingly, they have thrown away victories against Southampton and Cardiff this season by conceding injury-time equalisers.

  20. October 5, 2014 at 2:37 am

    real beauty page ibuprofen 400 mg tablet As a Contributing Editor for PC Magazine, John Delaney has been testing and reviewing monitors, HDTVs, PCs, servers, and other assorted hardware and peripherals for more than 14 years. A 13-year veteran of PC Magazine’s…

  21. October 5, 2014 at 2:38 am

    I’d like to cancel a cheque injectable imitrex cost So as soon as Sarah decided that serving a mission was what she wanted to do, she decided to fool her father by not telling him about submitting her papers and lead him into believing that she was about to get engaged.

  22. October 5, 2014 at 2:38 am

    Will I be paid weekly or monthly? propranolol 60 mg price The study also found that the biggest and fastest fish in the study, steelhead, are the most likely to fall prey to predators. Although the team did not investigate the reasons for that, steelhead may be more vulnerable to fish-eating birds like terns and cormorants because they swim closer to the surface than chinook salmon, according to McMichael.

  23. October 5, 2014 at 2:39 am

    I need to charge up my phone no prescription terbinafine tablets Seven seconds in, Marcus Johansson fed Ovechkin on a back-door play for a one-timer that made Bishop little more than a pylon in a practice drill to pull the Capitals within one. A little over two minutes after that tally, Ovechkin scored again – this time on a one-timer after a feed from Green — to tie the game at 4, secure a hat trick and overtake Bondra in the record books.

  24. October 5, 2014 at 7:35 am

    I read a lot buy cheap lasix online Lunch with Philips raised only £4,000, while a meal with his rivals at Sainsbury’s – boss Justin King and wingmen Mike Coupe and Judith Batchelar – raised more than seven times that amount, at over £30,000.

  25. October 5, 2014 at 7:35 am

    Which university are you at? lisinopril for Actor Paul Walker has died. He was best known for his role in the “Fast & Furious” movie series. The 40-year-old actor was a passenger in a car that crashed in North Los Angeles. Walker was working on the seventh installment of the “Fast & Furious” series. And as NPR’s Nathan Rott reports, he was also working on a life post-acting.

  26. October 5, 2014 at 7:35 am

    Could I have a statement, please? levlen cost For some leaders, the sudden focus on mental health looked like a dodge to avoid a serious discussion of meaningful gun safety measures. But no matter. The nation and most states must do more to help people with serious psychiatric problems.

  27. October 5, 2014 at 12:33 pm

    A Second Class stamp order gabapentin online Since I’m a New Zealander, rugby has always had a special place in my heart. In the early 90s, rugby was changing, rapidly and dramatically. In the course of reporting what happened in international rugby between August 1992 and July 1993, Jones offered a wise and perceptive analysis of the hows and the whys, a clear-eyed and sure-footed appraisal of what the rush towards professionalism might mean for the game. While he didn’t hide his anxieties about what might be lost, it was clear his love of rugby wouldn’t waver. It’s rare indeed to find a rugby book written with such crisp intelligence and such a delicate touch.

  28. October 5, 2014 at 12:33 pm

    My battery’s about to run out ibuprofen acetaminophen QUIST-ARCTON: Monday seems to be not a day of rest but a day of preparation for Tuesday’s official memorial service. And that will be in a huge soccer stadium in Soweto. We’re told that President Obama and the first lady will be attending and also former President George W. Bush and Mrs. Laura Bush and former President Clinton. And then the mortal remains of President Mandela will be laid in state in Pretoria, in the capital. And from then, he will be taken to Qunu. That’s his rural homestead. That is where Nelson Mandela will be laid to rest on Sunday.

  29. October 5, 2014 at 12:34 pm

    Children with disabilities gabapentin 800mg (neurontin) anticonvulsant Flog shares in miner Hochschild, JPMorgan advises. The broker thinks an update this week showed an improvement in profitability but, with commodity prices under pressure and the valuation of the shares “full”, it rated it underweight with a 127p target for shares that are around 135p.

  30. October 5, 2014 at 5:26 pm

    What do you do? paxil vs. prozac for pe According to Aishah’s family, the Malaysian government became aware of her political activities in London and warned her in the 1970s that it would make it very difficult for her to return home.

  31. October 5, 2014 at 5:28 pm

    Could you transfer $1000 from my current account to my deposit account? buy liquid nolvadex There were reports that people may have been trapped inside, but they could not be immediately confirmed. Glasgow ska band Esperanza were playing when the helicopter began to fall through the ceiling, witnesses said.

  32. October 5, 2014 at 10:36 pm

    On another call dapoxetine for sale On Tuesday, the city’s solicitor, Rick O’Connor, told the committee he’ll be seeking all costs and damages from Genivar, the company responsible for the original design, but that it’s not as simple as suing Genivar for $4.6 million.

  33. October 5, 2014 at 10:37 pm

    Can you put it on the scales, please? order prednisone online As the Labour leadership accused the coalition of launching a smear campaign over the party’s links with the disgraced former Co-op Bank chairman Paul Flowers, a transcript of an interview with Balls in 2010 showed that he highlighted his role in helping to create Britain’s “first ever ‘super-mutual’.”

  34. October 5, 2014 at 10:38 pm

    Can you hear me OK? dapoxetine tablet The Spurs were able to outlast the Grizzlies with superior depth. Their bench was terrific in the middle of the game – Ginobili and Marco Belinelli repeatedly hit big shots – and then the Spurs’ starters did the rest to hold on for the win.

  35. October 6, 2014 at 8:58 am

    Whereabouts are you from? risperidone mg The company received $2 million in tax subsidies to build its North American headquarters in LA. But the California Labor Commissioner’s office has now hit BYD with a $99,000 fine. The plant in Lancaster, which has yet to open, is under investigation for paying workers below minimum wage. However, Austin argues BYD has always complied with California labor laws.

  36. October 6, 2014 at 8:58 am

    Looking for work retin a micro pump wrinkles Could this be the last time English batsmen will bat on the Waca deck? The ground is now comfortably the worst on the entire Ashes circuit (including the ten grounds in England) and is in desperate need of modernisation. It would be a shame if one of the world’s iconic cricket grounds boasting the one of the best pitches in the game faded from the Test rota but that is the danger facing officials at the Western Australia Cricket Association.

  37. October 6, 2014 at 8:59 am

    Could I have , please? order silagra The obvious solution is to train the immune system to recognize meningitis B by some other characteristic. But there are hundreds of strains, and sometimes the only thing they all have in common is that darned sugar coating.

  38. October 6, 2014 at 8:59 am

    What’s your number? order sildenafil citrate
    It is the risk to this agreement that is at the heart of the problem. Indeed, US opponents of the treaty at the time pointed to the case of a US defence contractor that illegally transferred classified night-vision technology to China, Singapore – and Britain.

  39. October 6, 2014 at 9:00 am

    Another year order sildenafil citrate
    “The allegations come at a particularly difficult time for Sheriff Lee Baca, who is facing several challengers in his campaign for re-election next year. Sheriff Baca has repeatedly said that he has responded to all charges of misconduct as soon as he was aware of them, but critics like the American Civil Liberties Union say that he willfully ignored persistent problems.”

  40. October 6, 2014 at 6:57 pm

    Have you got any experience? tetracycline order Crain's said the information is unofficial, and it quoted “sources,” who were quick to caution that the deals could still fall through. Elmhurst City Manager Jim Grabowski told Elmhurst Patch last month that the store's future was unknown.

  41. October 6, 2014 at 6:57 pm

    Recorded Delivery online tetracycline An environmental statement running to almost 50,000 pages was published on Monday alongside the hybrid bill, which is, effectively, an application for planning permission to build the entire first phase of the route, from London to Birmingham.

  42. October 6, 2014 at 6:57 pm

    What sort of work do you do? tenormin online But his approach to publishing means his work is rare, which means there’s always a scramble when anything new becomes available. Maybe the weirdest thing of all is that the winning bid for the eBay auction was in British pounds, for about $107. Someone got a bargain.

  43. October 6, 2014 at 6:57 pm

    I’m happy very good site buy cheap imipramine “We try to provide our contributions very early in year, and we try to do it in a way that allows them to plan and program effectively,” Lawson says. “If we use our 2014 contributions to meet 2013 needs, then the needs will just become greater in 2014.”

  44. October 6, 2014 at 6:58 pm

    Could I have a statement, please? generic atenolol Yuri Zarutsky, who admitted to being the masked attacker who threw acid in Filin’s face in January, was sentenced to 10 years in prison. Andrei Lipatov, who drove Zarutsky to the scene, was sentenced to four years.

  45. October 7, 2014 at 12:22 am

    Excellent work, Nice Design taking 300 mg wellbutrin xl The overriding priority throughout will be continued safe and smooth delivery and, as recommended by the Public Accounts Committee in their recent report on Universal Credit, this will take precedence over meeting specific timings.

  46. October 7, 2014 at 12:22 am

    I’ve got a part-time job zetia 20 mg His last big takedown – the bust of a Shreveport drug ring and biker gang – went awry with the son of the drug lord dying in a hail of bullets. So, Brooker, a single dad, decides a quieter, less lethal way of life might be in order.

  47. October 7, 2014 at 10:38 am

    What’s the current interest rate for personal loans? buy nizagara online (Medical Xpress)—A recently published study strongly suggests men succumb to sexual temptations more than women—for example, cheating on a partner—because they experience strong sexual impulses, not because they have …

  48. Stephanie
    October 7, 2014 at 3:48 pm

    I’m in my first year at university cheaper alternative abilify Genes are the blueprints for the proteins that act as the building blocks of the body’s tissues. The process of carrying out these genetic plans is called gene expression. After a python eats, its gene expression changes rapidly. Genes that may have been quiet suddenly come alive as their instructions are expressed. Some genes that are expressed steadily in daily life become more active, churning out massive amounts of proteins that promote growth or metabolism.

  49. October 7, 2014 at 8:53 pm

    I work with computers where to buy diprolene Savient has been on the look-out for a buyer pretty much since Krystexxa (pegloticase) was approved by the US Food and Drug Administration in September 2010 for the treatment of gout in adults who do not respond to conventional therapy. No purchaser had been found until bankruptcy proceedings began and it was announced that a $55 million offer from Sloan Holdings CV would serve as a 'stalking horse' bid.

  50. October 8, 2014 at 2:12 am

    I’ll call back later apo clomipramine 50 mg Compounders that pay a fee to become registered outsourcers would be subject to FDA oversight, inspections of facilities and products and would be required to follow good manufacturing practices laid out by the agency.

  51. October 8, 2014 at 2:13 am

    Where do you live? purchase avapro In other hoax news, a website that looked like it might be a teaser for Fallout 4 has been revealed as a fan creation. That’s an especially strange hoax, because Bethesda is more than likely actually making the game, just not teasing it quite yet. Someone, apparently, got a little overeager. Remember, you can’t believe everything you read on the internet.

  52. October 8, 2014 at 2:14 am

    Why did you come to ? avapro 300 “Investors are clearly watching every move the Fed makes, but when you look for evidence that in the long term equity prices are higher than would be justified by fundamentals, there’s no evidence of that,” says Susan Lund, a partner in the firm.

  53. October 8, 2014 at 7:25 am

    Just over two years how much does benicar cost The dispute over standard-essential patents were highlighted in August when the Obama administration vetoed an import ban on some Apple products in the U.S., citing concerns about patent holders gaining leverage as well as potential harm to consumers. Samsung had been seeking a ban against some older Apple products claiming that they infringe on Samsung’s standard-essential patents.

  54. October 8, 2014 at 7:25 am

    Did you go to university? what is the cost of celebrex The landmark November 24 interim accord between the Islamic Republic and the United States, France, Germany, China, Russia and Britain is seen as a first step towards resolving a decade-old dispute that has stirred fears of a new Middle East war.

  55. October 8, 2014 at 7:26 am

    On another call bactrim 500 mg Directed by Paul Dugdale, the two-hour documentary includes rare backstage and behind-the-scenes footage in addition to the concert highlights. It came out on DVD and Blu-ray on November 11th just after a worldwide theatrical release. 

  56. October 8, 2014 at 7:26 am

    Could you send me an application form? cheap bactrim The children spent three years in America, and by all accounts Shirley thrived, but reports of her achievements won very modest praise. When the family friend with whom the children lived mentioned her brightness, Brittain suggested that Shirley be reminded that her mother ‘wrote five novels before the age of 11’; when the headmistress reported that Shirley was doing exceptionally well despite being a year younger than the other children in her class, Vera replied that she should know that ‘her mother at the same age was three years younger than her classmates and managed somehow or other to be near the top of the form.’ Shirley’s popularity worried Brittain, who urged her daughter to spend more time on her studies. The two children also had to thwart a plan by their mother to separate them and ship Shirley off to boarding school in Texas.

  57. October 8, 2014 at 12:28 pm

    What sort of music do you like? generic ciprofloxacin What the Obama administration needed was a 21st century version of Amazon for health insurance. What it has instead is more like Amazon when it still just sold books. If that doesn’t change, Obamacare is doomed.

  58. October 8, 2014 at 12:28 pm

    Could I take your name and number, please? order combivent online On Thursday, when Tottenham traveled to Norway to face Tromso in the Europa League, he had an opposing fan removed from the stand because he could hear him chant “You’ll be sacked in the morning!”

  59. October 8, 2014 at 12:29 pm

    I can’t stand football cipro xr 500mg Without supplies, all construction projects but one are on hold, and the price of fuel has already doubled. Electricity is supplied regularly for only six hours a day, and gasoline for power generators will soon become a rare commodity here. “This is an emergency, and we are doing our best to deal with it,” said Hatem J. Owida, deputy minister of economy in Gaza.

  60. October 8, 2014 at 12:29 pm

    What qualifications have you got? buy cheap combivent “I think remembering him as a truly multifaceted figure with a wide array of different skills and abilities reminds us that his success wasn’t preordained—it had to be earned over a lifetime,” Mr. Rhodes said.

  61. October 8, 2014 at 5:27 pm

    I’ve got a full-time job purchase diflucan “”Making your own food and knowing all of the ingredients is obviously better,” a Natural Machines spokesperson said, “but it does require more time from you in the kitchen versus opening a bag or a box of something that is processed, frozen or already prepared.”

  62. October 8, 2014 at 5:28 pm

    Where are you from? amitriptyline hcl 25mg Why has the alphabet got only 25 letters at Christmas? Give up? No-el, no-el, no-el, no-el… Which two letters are always jealous? N-V. What begins with T, ends with T and is filled with T? A teapot. If you like gags like this then Alphabetical is just your cup of char. In fact, forget party crackers – when you settle down to the turkey and trimmings this year simply make sure you have this book to hand. There’s even a chapter devoted to family-friendly alphabet games: perfect for playing after the Queen’s been on.

  63. October 8, 2014 at 10:38 pm

    I’m at Liverpool University purchase estradiol online “It will take him a wee bit of time to totally get the idea across. (His players) have been used to playing a certain way. Now they are wanting to connect it more through midfield, so that longer ball from behind to the striker is not in as much prominence.”

  64. October 8, 2014 at 10:39 pm

    I’d like a phonecard, please estrace estradiol “It’s right at the edge, isn’t it?” McCaw said. “This business is about personal contact between two people for money…people have different opinions of what they think Madison is and sometimes people are shocked by pushback.”

  65. October 9, 2014 at 8:52 am

    The United States hoodia 57 At the heart of the dispute is the number, often quoted by government officials and the labour minister, that in 80 per cent of cases where a worker has refused work due to danger, an investigation and, in some cases an appeal, has made a finding of no danger.

  66. October 9, 2014 at 8:52 am

    A book of First Class stamps buy propranolol 40mg “Our priority is the safety and wellbeing of our students, staff and the wider community, and we are concerned where any protest poses a potential hazard to protesters or bystanders, or causes unwarranted disruptions to study or work, or damage to property.

  67. October 9, 2014 at 8:52 am

    Thanks for calling buy terbinafine tablets online Newlyweeds is a rare movie about stoners that treats pot addiction seriously, carving out a space of its own in a naturalistic middle ground between the familiar standards of surreal comedy and moralistic drama.

  68. October 9, 2014 at 8:52 am

    Thanks for calling buy ibuprofen By moving Fielder’s nine-year, $214 million contract – which has $168 million left to pay – the Tigers may have created enough payroll room to keep newly minted AL Cy Young Award winner Max Scherzer.

  1. June 17, 2015 at 2:16 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: