"Working on the complexity that is always indirectly implied by simpilicity."

Sample Mixins for HttpRequestBase to use with Asp.Net MVC

Being a semi avid user of rails for my day job, you tend to miss a couple of things that rails has that is not in Asp.Net's MVC framework. It is a great start and the control over the html (minus laziness of whoever ever developed their "Html.DropDownList" extension method, grrr INDENT YOUR NEW LINES!!), is much greater than what webforms gives you. One of the missing things that I miss is the request.xhr?, request.post?, etc methods that end to be helpful when deciding if this is an AJAX call or an actual action call to return the correct page.

So how do you determine if the request is an ajax request or just a regular page request. What about enforcing that a page is SSL?  What about doing different things depending if the request is a GET or POST? 

So after some googling about headers, rails, and such: here are the first go around of extension methods for HttpRequestBase that should come in handy.

public static class ControllerMixins
{

		public static bool IsPost(this HttpRequestBase obj)
		{
			return obj.Headers["REQUEST_METHOD"].ToLower() == "post";
		}

		public static bool IsGet(this HttpRequestBase obj)
		{
			return obj.Headers["REQUEST_METHOD"].ToLower() == "get";
		}

		public static bool IsXhr(this HttpRequestBase obj)
		{
			string value = obj.Headers["HTTP_X_REQUESTED_WITH"];
			return (!string.IsNullOrEmpty(value) && value.ToLower() == "xmlhttprequest");
		}

		public static bool IsSSL(this HttpRequestBase obj)
		{
			return obj.Headers["HTTPS"] == "on" ||
				obj.Headers["'HTTP_X_FORWARDED_PROTO'"] == "https";
		}
}

Labels: , , , , ,