C# – Detect if action is a POST or GET method

asp.net-mvcc

In MVC 3, is it possible to determine if an action is a result of a POST or GET method? I know you can decorate the actions with [HttpPost] and [HttpGet] to fire a specific action if one of those happens. What I'd like to do is leave those attributes off and programmatically determine which one caused the action.

The reason is, because of the way my search page is architected, I'm storing the search model in TempData. The initial search causes a POST to the search results page, but the paging links are all just links to "/results/2" (for page 2). They examine TempData to see if the model is in there an use it if so.

This causes problems when someone uses the back button to go to the search form and resubmit it. It's still picking up the model in TempData instead of using the new search criteria. So if it's a POST (i.e. someone just submitted the search form), I want to clear out TempData first.

Best Answer

The HttpMethod property on the HttpRequest object will get it for you. You can just use:

if (HttpContext.Current.Request.HttpMethod == "POST")
{
    // The action is a POST.
}

Or you can get the Request object straight off of the current controller. It's just a property.