CONNECT WITH US

Featured Post

ASP.NET MVC: HttpPatch action filter

Get article update by Email
ASP.NET MVC: HttpPatch

HttpPatch action filter attribute confirm that specified method should be available only via HTTP PATCH request. HttpPatch action filter is new in MVC 4. HTTP PATCH verb is relatively new and it is used to modify an existing HTTP resource. HTTP PUT allow us to create or replace existing HTTP resource but we cant modify existing resource with HTTP PUT. This is where HTTP PATCH comes in picture.

Attribute Usage: Only method

Sample Code:

[HttpPatch]
public ActionResult About()
{
    return View();
}

Alike other action filter, We can’t access such method with other than HTTP PATCH verb. If we try to access it with other HTTP verb then it will fail and return HTTP 404 not found error.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: HttpOptions action filter

Get article update by Email
ASP.NET MVC: HttpOptions

HttpOptions action filter specifies that, user should access this action method via HTTP OPTIONS request. Trying to access other than HTTP OPTIONS verb will fail and result in HTTP 404 not found error. This action filter is new in MVC 4. With HTTP OPTIONS verb client can determine the capabilities of the server.

Attribute Usage: Only method

Sample Code:

[HttpOptions]
public ActionResult About()
{
    return View();
}

Alike other action filter, We can’t access such method with other than HTTP OPTIONS verb.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: HttpHead action filter

Get article update by Email
ASP.NET MVC: HttpHead

HttpHead action filter specifies that, this action method should be only accessible via HTTP HEAD request. HttpHead action filter is new in MVC 4. HTTP HEAD request is similar to GET request but it instruct server to send only response header, and not whole response body.

Attribute Usage: Only method

Sample Code:

[HttpHead]
public ActionResult About()
{
    return View();
}

Alike other action filter, We can’t access such method with other than HTTP HEAD verb.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: ActionName action filter

Get article update by Email
ASP.NET MVC: ActionName

ActionName action filter allow us to change name of action method while we are accessing it via url. By default we can access action method with {controller}/{action} pattern but in some case we don’t want action method to be accessible by its name. So in such case we can use ActionName action filter attribute.

We can pass custom action name as an argument with this attribute. We also need to create or rename existing view to custom action name passed as argument. Because once we use ActionName attribute, MVC framework will consider this custom action name as a name of action and actual method name will not be taken in consideration.

Attribute Usage: Only method

Sample Code:

[ActionName("AboutBlog")]
public ActionResult About()
{
    return View();
}

Note: ActionName attribute require view with similar name to argument passed. In above case return View() will look for AboutBlog.cshtml and not for About.cshtml.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: HttpPut action filter

Get article update by Email
ASP.NET MVC: HttpPut

In this ASP.NET MVC action filter tutorial series, HttpPut is 4th attribute which allow developer to restrict action method access based on HTTP verb. As name suggest, HttpPut marked action method will be accessible only via HTTP PUT verb. Similar to HttpPost, HttpGet & HttpDelete, HttpPut also inherited from ActionMethodSelectorAttribute.

Attribute Usage: Only method

Sample Code:

[HttpPut]
public ActionResult About()
{
    return View();
}

Alike other action filter, We can’t access HttpPut marked method with other than HTTP PUT verb.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: HttpDelete action filter

Get article update by Email
ASP.NET MVC: HttpDelete

HttpDelete action method selector attribute is used whenever we want to restrict action method to be accessible only via HTTP DELETE verb. Similar to HttpPost & HttpGet, HttpDelete also inherited from ActionMethodSelectorAttribute.

Attribute Usage: Only method

Sample Code:

[HttpDelete]
public ActionResult About()
{
    return View();
}

Once we marked action method with HttpDelete attribute, it will throw an HTTP 404 not found error if we try to access it with other HTTP verb.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: HttpGet action filter

Get article update by Email
ASP.NET MVC: HttpGet

HttpGet action method selector attribute restrict action method so that marked action method would be served for only HTTP GET verb. Similar to HttpPost, HttpGet also inherited from ActionMethodSelectorAttribute.

Attribute Usage: Only method

Sample Code:

[HttpGet]
public ActionResult About()
{
    return View();
}

When action method is decorated with HttpGet attribute, then those action methods are accessible only via HTTP GET request. Request via other HTTP method will fail and return HTTP 404 not found error.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: NonAction action filter

Get article update by Email
ASP.NET MVC: NonAction

In ASP.NET MVC, every public method of controller is accessible via url regardless of return type, so if we have created any public method in controller which is not intended to serve as action method then also it is accessible via url. One solution is that keep this method as private or protected but some time we need to keep this method as public. This is where NonAction attribute comes in picture. First have a look at public method in following code.

Sample Code:

public string GetBlogName()
{
    return "dotnetExpertGuide.com";
}

As we can see that we can access this method via url. Now mark this method with NonAction attribute as follow.

Attribute Usage: Only method

Sample Code:

[NonAction]
public string GetBlogName()
{
    return "dotnetExpertGuide.com";
}

Now try to access this method via url. It will return HTTP 404 not found error. So whenever we want to create public method in controller which is not intended for action method or in other word which is not returning Action Result those method should be marked with NonAction action method selector attribute. NonAction is inherited from ActionMethodSelectorAttribute.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: RequireHttps action filter

Get article update by Email
ASP.NET MVC: RequireHttps

As name suggests, RequireHttps attribute indicate that this action method should only accessible by SSL or HTTPS. Whenever action methods are marked with RequireHttps, at that time we cannot browse it with HTTP protocol. If we try to browse it with HTTP then it will be redirected to HTTPS url. We can also use this attribute at controller level.

Attribute Usage: Controller & Method

Sample Code:

[RequireHttps]
public ActionResult SignIn()
{
    return View();
}

As we can see in above image that request to HTTP url will issue an HTTP 302 redirection and it will be redirected to HTTPS url. When RequireHttps is applied at controller level, all action method within controller would be only accessible via HTTPS. We should apply this attribute, wherever we are obtaining sensitive data from user for e.g. login credential, credit card information, etc. I think RequireHttps attribute is one of the best examples which shows how ASP.NET MVC framework simplifies web developments.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: HttpPost action filter

Get article update by Email
ASP.NET MVC: HttpPost

In ASP.NET MVC controller, HttpPost action method selector attribute let us restrict action method so that specified action method is only accessible via HTTP POST verb or request. HttpPost is inherited from ActionMethodSelectorAttribute which is used to validate action method selection based on controller context.

Attribute Usage: Only method

Sample Code:

[HttpPost]
public ActionResult About()
{
    return Json(Model);
}

Generally we should mark action method with HttpPost whenever we are returning Json result from action method in other word whenever action method is consumed by only AJAX request at that time we should mark it with HttpPost attribute. However this is not the only scenario. If we try to access action method with other than POST verb then it will throw HTTP 404 not found error.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET 4.5 & MVC 4: Revisiting IBundleTransform

Get article update by Email

Earlier almost year ago, when MVC 4 developer preview version released at that time I have blogged on how to create custom transform type for bundling in ASP.NET 4.5 & MVC 4. There are some changes in System.Web.Optimization since developer preview release to RC. As far as this post concerns, I am more interested in changes in IBundleTransform interface so I am rewriting old post which include changes in IBundleTransform.

Web optimization frameworks include two defaults transform type JsMinify and CssMinify which is used by ScriptBundle and StyleBundle respectively. However we can create our own custom transform type to processe references as per our need. To create custom transform type, we need to create class which implements IBundleTransform interface.

IBundleTransform interface define a method named Process which process bundle response. In developer preview version, Process method had only one parameter of type BundleResponse, however onwards RC release, Process method introduced one more parameter of type BundleContext. In this post, we will see how we can utilize this additional parameter while creating our custom transform type.

BundleContext

As name suggest, with BundleContext, we can get information about bundles which could include existing bundle information, bundle url, HTTP context for bundle, etc. Following is the list of all property of BundleContext.

  • BundleContext.BundleCollection : We can get collection of all bundles including default and custom bundle in application through this property.
  • BundleContext.BundleVirtualPath : This property expose virtual bundle url i.e. ~/bundles/MyBundle.
  • BundleContext.HttpContext : This property is type of HttpContextBase, and we can have access of HTTP context through this property. This is very much useful property when we are creating transform type which generate dynamic response. For e.g. we can access query string parameter passed to bundle url (~/bundles/MyBundle?id=123) through this property (context.HttpContext.Request.QueryString["id"]) and we can use it to create dynamic bundle response.
  • BundleContext.UseServerCache : Default value of this property is true. It means only first request to bundle url will be intercepted by transform types and once response is generated it will be stored in server cache and further request to bundle url will be served from server cache without processing it. This will help to reduce bundle processing time and to increase performance. If we set BundleContext.UseServerCache to false then all request will be processed by transform type this is only necessary when bundle url are generating dynamic response. See detailed walkthrough later in this post showing how to use this property in accordance with BundleResponse.Cacheability.
  • BundleContext.EnableInstrumentation : Default value of this property is false. This is used for tracing and analysis purpose. We can check value of this property and can write tracing code accordingly. We can also set true to this property to enable instrumentation for further lifecycle of Web optimization frameworks for current bundle request.

BundleResponse

Now let us recall BundleResponse parameter from old post. BundleResponse is used to retrieve list of files included in bundle so we can process it and generate response for bundle. As BundleResponse is used to generate response of bundles, it needs to take care of two primary properties of generated response. One is response content type and another one is HTTP Cache-Control header. So BundleResponse also expose properties for the same. Following is the list of all properties in BundleResponse class.

  • BundleResponse.Files : This is IEnumerable collection of files which is included in bundle. We can iterate through this collection and process file content to generate bundle response.
  • BundleResponse.ContentType : Through this property, we can set content type for bundle so that browser can render it appropriately. Default content type "text/html".
  • BundleResponse.Cacheability : We can use this property to set Cache-Control HTTP header of bundled response. Default value of this property is Public.
  • BundleResponse.Content : Anything which we set as a value of this property, that content will be sent back to browser as a response of bundle.

Following is the complete code which shows how to create custom transform type and how we can use it with bundling.

public class CustomTransformType : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        string strBundleResponse = string.Empty;
        foreach (FileInfo file in response.Files)
        {
            // PROCESS FILE CONTENT 
        }
        response.Content = strBundleResponse;
    }
}
 
Bundle myBundle = new Bundle("~/bundles/MyBundle", new CustomTransformType());
myBundle.Include("~/path/to/file");
bundles.Add(myBundle);

Bundle and truly dynamic response

As we noted earlier, we can set BundleContext.UseServerCache to false in order to process all bundle request and generate dynamic response. Let try to simulate this by small walkthrough and see it works or we need to take care any additional parameter.

public void Process(BundleContext context, BundleResponse response)
{
    context.UseServerCache = false;
    response.Content = DateTime.Now.ToString();
}

We are returning current date time with UseServerCache set to false. Now try to hit bundle url multiple times by pressing F5. Oops… it seems it has processed bundle response only first time. Let dig more into this, open another browser and hit same url… ahmm it seems it has processed bundle response one more time… again press F5 multiple times…bad luck

As we can see, it seems (read again it seems) it is processing bundle response only first time for separate client (is it really? nop). Nop this is not the case. In fact this is how client deals with it due to HTTP cache control header. Confused? See response header of bundle url to get more information.

As we noted earlier default value of BundleResponse.Cacheability is Public. So even if we have set BundleContext.UseServerCache to false then also due to Expires response header and Public Cache-Control header client is not sending request back to server. So in this case we need to also set BundleResponse.Cacheability to NoCache. We can also set it to Private but in some client we need to press Ctrl + F5 to refresh bundle response.

public void Process(BundleContext context, BundleResponse response)
{
    context.UseServerCache = false;
    response.Cacheability = HttpCacheability.NoCache;
    response.Content = DateTime.Now.ToString();
}

After setting BundleResponse.Cacheability to NoCache try to refresh bundle url again now it is re generating bundle response on each request.

So this was all about custom transform type for bundling in ASP.NET 4.5 & MVC 4. Stay tuned to know about how we can utilize bundling to generate response from other than only file content.

For more post on MVC 4 you can read MVC 4 article series here and follow me on twitter to get latest tips and links on twitter.

Check out this index post on ASP.NET Web Optimization Framework (a.k.a Bundling & Minification) to read other post on same.

Read More

ASP.NET & MVC 4: Cookieless domain for bundling and static resources

Get article update by Email

Last week, one reader of this blog asked, how to setup cookieless domain to serve bundle response and other static resources in ASP.NET application. Yes it is very much necessary and one of the web performance guideline that static resource should be served from cookieless domain for better performance. So here in this post we will see how to setup ASP.NET application and IIS for cookieless domain with minimal code changes and deployment task. You can directly jump to IIS setup section if you don't want to read detailed information.

Cookieless domain and IIS

Logically we can’t configure IIS or any other web server so that it does not accept or set cookie for domain. This is because cookie is stored in client side and more importantly it is component of client and not of server. Hence we can’t configure IIS or any other web server to disable cookie.

So what’s the solution for that? As a developer, we need to take care that we do not set cookie for static or cookieless domain by server side scripting or client side scripting. We need to also take care that any third party JavaScript also do not set cookie for static domain. Because once cookie is set, it will be used for all subsequent requests until it is expired or removed by client.

ASP.NET & Cookie

By default ASP.NET session id is stored in cookie and even if we use cookieless session then also there are chances that cookie might be set by other code or sometime by HTTP handler or HTTP module also. Conclusion is that we can’t use our main domain (for e.g. www.domain.com) to serve static content and we need to configure another domain or website (for e.g. static.domain.com) to serve static content and we need to move static resource to static.domain.com and refer that cookieless domain from within www.domain.com pages.

That’s sound pretty much cool and easy too but ASP.NET 4.5 & MVC 4, introduced bundling which bundle all JavaScript and CSS files dynamically at runtime by HTTP module. As behind the scene bundling is using HTTP module, again we need to setup ASP.NET application for static.domain.com and the same time we also need to take care that static.domain.com must not serve dynamic response other than bundle response. So here are the step by step tutorial starting with IIS setup to achieve the same.

IIS Setup

Create two websites in IIS. One for our main domain i.e. www.domain.com and another for cookieless domain i.e. static.domain.com. Now point these both website to same physical directory i.e. C:\inetpub\www.domain.com. Yeah we don’t want to deploy at two places and still static.domain.com will serve only static resource including bundle response and still there will be not any additional request filtering overhead for www.domain.com. Continue reading to know more ;)

Redirect domain.com to www.domain.com

Once you setup domain in IIS now its time to configure www.domain.com so that any domain.com request must be redirected to www.domain.com because cookie set for domain.com will also be shared by all sub domain including static.domain.com hence it is much important steps. You can read this post on how to redirect domain.com to www.domain.com.

Code changes

Now add following three app settings in web.config. StaticSiteName is the name of website in IIS for static.domain.com.

<appSettings>
  <add key="StaticSiteName" value="static.domain.com"/>
  <add key="StaticDomain" value="http://static.domain.com"/>
  <add key="MainDomain" value="http://www.domain.com"/>
</appSettings>

We will use this StaticSiteName to dynamically register HTTP module only for static.domain.com so static resource filtering will be enabled only for static.domain.com and not for www.domain.com even if we are sharing same deployment.

We will use PreApplicationStartMethod and Microsoft.Web.Infrastructure to dynamically register HTTP module in pre-application startup stage.

Following is the code snippet for the same.

public class PreApplicationStart
{
    public static void Start()
    {
        string strStaticSiteName = ConfigurationManager.AppSettings["StaticSiteName"];
        string strCurrentSiteName = HostingEnvironment.SiteName;
 
        if (strCurrentSiteName.ToLower() == strStaticSiteName.ToLower())
        {
            DynamicModuleUtility.RegisterModule(typeof(StaticResource));
        }
    }
}
    
public class StaticResource : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }
 
    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        string strUrl = context.Request.Url.OriginalString.ToLower();
 
        //HERE WE CAN CHECK IF REQUESTED URL IS FOR STATIC RESOURCE OR NOT
        if (strUrl.Contains("Path/To/Static-Bundle/Resource") == false)            
        {
            string strMainDomain = ConfigurationManager.AppSettings["MainDomain"];
            context.Response.Redirect(strMainDomain);
        }
    }
 
    public void Dispose()
    {
    }
}

In above code snippet we are registering StaticResource HTTP module only if pre application start method is fired for static.domain.com and then after if current request is not for static or bundle response then we are redirecting user to our main domain i.e. www.domain.com. This is also very much important because if we do not filter request then it is likely possible that our main domain content could be available via static.domain.com. One more important thing is that we are registering HTTP module only for static.domain.com application context so request to www.domain.com will not be intercepted by StaticResource module so it could save fraction of second in overall response time :)

Now add following extension method for UrlHelper class.

public static class Extensions
{
    public static string StaticContent(this UrlHelper url, string contentPath)
    {
        string strStaticDomain = ConfigurationManager.AppSettings["StaticDomain"];
        return contentPath.Replace("~", strStaticDomain);
    }
}

Now we can use @Url.StaticContent() from view so that it will render static resource url with static.domain.com whether it is image, script, CSS, or bundles or wherever we want to refer cookieless domain. for e.g.

<link href="@Url.StaticContent("~/Content/Site.css")" rel="Stylesheet" />
<script src="@Url.StaticContent("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
<script src="@Url.StaticContent("~/bundles/jquery")" type="text/javascript"></script>
 
<img src="@Url.StaticContent("~/Images/heroAccent.png")" alt="" />

We can also override Styles.Render or Scripts.Render to serve script resource and style resource from cookieless domain.

Third party JavaScript and cookie

Often we are using third party widget in our web application so it may be possible that third party script can set cookie for domain.com and any cookie set for domain.com will be shared by all sub domain including static.domain.com so we need to configure third party JavaScript such a way that it set cookie for www.domain.com and not for domain.com. Following is the code snippet for configuring Google Analytics script to set cookie for www.domain.com. You can get more information here.

_gaq.push(['_setDomainName', 'www.domain.com']); 

By default Google Analytics set cookie for top level domain i.e. domain.com and that could be shared by all sub domain. We need to identify such third party JavaScript and accordingly we need to change it for truly cookieless domain.

See below images to see all above setup in action!

cookieless domain ASP.NET
cookieless domain ASP.NET
cookieless domain ASP.NET
cookieless domain ASP.NET

Reference

Hope this would be helpful. You can also follow me on @NandipMakwana to get latest tips.

Read More

ASP.NET: Register HttpModule at runtime

Get article update by Email

In the last post, we have seen how we can use PreApplicationStartMethod assembly level attribute to configure ASP.NET application at runtime. Taking it further, in this post we will see how to leverage PreApplicationStartMethod to register HTTP module dynamically at runtime. You can read more on PreApplicationStartMethod in this post here.

First of all we need to install/reference Microsoft.Web.Infrastructure assembly which provide API for registering HTTP module dynamically. To install Microsoft.Web.Infrastructure, type following in the Package Manager Console.

Once you installed Microsoft.Web.Infrastructure, you can use following code to register HTTP module runtime.

public class PreApplicationStart
{
    public static void Start()
    {
        Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility
            .RegisterModule(typeof(MyHttpModule));
    }
}

Please not that we can’t call above API from within Application_Start because HTTP module registration must be done before ASP.NET application start and it will throw an exception if you call it from other than PreApplicationStartMethod.

Hope this would be helpful and stay tuned for next post in a row on MVC 4. You can also follow me to get latest update via @NandipMakwana.

Read More

ASP.NET: PreApplicationStartMethod example

Get article update by Email

Few days back when I was exploring how ASP.NET 4.5 and MVC 4 bundling are implemented specially how bundle url are resolved at runtime. At that time I found that PreApplicationStartMethod is used to hookup bundle url. PreApplicationStartMethod is used to configure ASP.NET application at runtime. PreApplicationStartMethod is fired in early stage of application startup and hence it is executed before Application_Start event so we can’t get reference of HttpApplication or HttpContext from within PreApplicationStartMethod. To create Pre application start method, we need to create a class with static method and then after we have to hookup that method through PreApplicationStartMethod attribute.

public class PreApplicationStart
{
    public static void Start()
    {
        // Pre application startup configuration goes here
    }
}

In AssemblyInfo.cs, we need to add following line.

[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "Start")]

As we noted earlier we can’t refer HttpApplication or HttpContext here however we can access application related configuration through System.Web.Hosting.HostingEnvironment. Through hosting environment API, we can access current application settings as well Application Host settings for IIS.

PreApplicationStartMethod can be used for many purposes for e.g. registering HTTP module or HTTP handler at runtime and possibilities are unlimited. Yeah stay tuned for more exciting use of PreApplicationStartMethod.

You can get latest update via @NandipMakwana.

Read More