Monthly Archives: August 2015

Don’t run production ASP.NET Applications with debug=”true” enabled

One of the things you want to avoid when deploying an ASP.NET application into production is to accidentally (or deliberately) leave the <compilation debug=”true”/> switch on within the application’s web.config file.


Doing so causes a number of non-optimal things to happen including:


1) The compilation of ASP.NET pages takes longer (since some batch optimizations are disabled)

2) Code can execute slower (since some additional debug paths are enabled)

3) Much more memory is used within the application at runtime

4) Scripts and images downloaded from the WebResources.axd handler are not cached


This last point is particularly important, since it means that all client-javascript libraries and static images that are deployed viaWebResources.axd will be continually downloaded by clients on each page view request and not cached locally within the browser.  This can slow down the user experience quite a bit for things like Atlas, controls like TreeView/Menu/Validators, and any other third-party control or custom code that deploys client resources.  Note that the reason why these resources are not cached when debug is set to true is so that developers don’t have to continually flush their browser cache and restart it every-time they make a change to a resource handler (our assumption is that when you have debug=true set you are in active development on your site).


When <compilation debug=”false”/> is set, the WebResource.axd handler will automatically set a long cache policy on resources retrieved via it – so that the resource is only downloaded once to the client and cached there forever (it will also be cached on any intermediate proxy servers). If you have Atlas installed for your application, it will also automatically compress the content from the WebResources.axd handler for you when <compilation debug=”false”/> is set – reducing the size of any client-script javascript library or static resource for you (and not requiring you to write any custom code or configure anything within IIS to get it).


What about binaries compiled with debug symbols?


One scenario that several people find very useful is to compile/pre-compile an application or associated class libraries with debug symbols so that more detailed stack trace and line error messages can be retrieved from it when errors occur.


The good news is that you can do this without having the have the <compilation debug=”true”/> switch enabled in production.  Specifically, you can use either a web deployment project or a web application project to pre-compile the code for your site with debug symbols, and then change the <compilation debug=”true”/> switch to false right before you deploy the application on the server.


The debug symbols and metadata in the compiled assemblies will increase the memory footprint of the application, but this can sometimes be an ok trade-off for more detailed error messages.


The <deployment retail=”true”/> Switch in Maching.config


If you are a server administrator and want to ensure that no one accidentally deploys an ASP.NET application in production with the <compilation debug=”true”/> switch enabled within the application’s web.config file, one trick you can use with ASP.NET V2.0 is to take advantage of the <deployment> section within your machine.config file.


Specifically, by setting this within your machine.config file:




<deployment retail=”true”/>




You will disable the <compilation debug=”true”/> switch, disable the ability to output trace output in a page, and turn off the ability to show detailed error messages remotely.  Note that these last two items are security best practices you really want to follow (otherwise hackers can learn a lot more about the internals of your application than you should show them).


Setting this switch to true is probably a best practice that any company with formal production servers should follow to ensure that an application always runs with the best possible performance and no security information leakages.  There isn’t a ton of documentation on this switch – but you can learn a little more about it here.

ASP.NET: Session.SessionID changes between requests

Why does the property SessionID on the Session-object in an ASP.NET-page change between requests?

I have a page like this:

    SessionID: <%= SessionID %>

And the output keeps changing every time I hit F5, independent of browser.

This is the reason

When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application’s Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.

So basically, unless you access your session object on the backend, a new sessionId will be generated with each request


This code must be added on the file Global.asax. It adds an entry to the Session object so you fix the session until it expires.

protected void Session_Start(Object sender, EventArgs e) 
    Session["init"] = 0;

Web API Content Negotiation

Inside Web API Content Negotiation

“Content negotiation” is often used to describe the process of inspecting the structure of an incoming HTTP request to figure out the formats in which the client wishes to receive responses. Technically, though, content negotiation is the process in which client and server determine the best possible representation format to use in their interactions. Inspecting the request typically means looking into a couple of HTTP headers such as Accept and Content-Type. Content-Type, in particular, is used on the server for processing POST and PUT requests and on the client for choosing the formatter for HTTP responses. Content-Type is not used for GET requests.

The internal machinery of content negotiation, however, is much more sophisticated. The aforementioned scenario is the most typical—because of default conventions and implementations—but it isn’t the only one possible.

The component that governs the negotiation process in Web API is the class called DefaultContentNegotiator. It implements a public interface (IContentNegotiator), so you can replace it entirely if needed. Internally, the default negotiator applies several distinct criteria in order to figure out the ideal format for the response.

The negotiator works with a list of registered media type formatters—the components that actually turn objects into a specific format. The negotiator goes through the list of formatters and stops at the first match. A formatter has a couple of ways to let the negotiator know it can serialize the response for the current request.

The first check occurs on the content of the MediaTypeMappings collection, which is empty by default in all predefined media type formatters. A media type mapping indicates a condition that, if verified, entitles the formatter to serialize the response for the ongoing request. There are a few predefined media type mappings. One looks at a particular parameter in the query string. For example, you can enable XML serialization by simply requiring that an xml=true expression is added to the query string used to invoke Web API. For this to happen, you need to have the following code in the constructor of  your custom XML media type formatter:

MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "text/xml"));

In a similar way, you can have callers express their preferences by adding an extension to the URL or by adding a custom HTTP header:

MediaTypeMappings.Add(new UriPathExtensionMapping("xml", "text/xml"));
MediaTypeMappings.Add(new RequestHeaderMapping("xml", "true",
  StringComparison.InvariantCultureIgnoreCase, false,"text/xml"));

For URL path extension, it means the following URL will map to the XML formatter:


Note that for URL path extensions to work you need to have an ad hoc route such as:

  name: "Url extension",
  routeTemplate: "api/{controller}/{action}.{ext}/{id}",
  defaults: new { id = RouteParameter.Optional }

For custom HTTP headers, the constructor of the RequestHeaderMapping class accepts the name of the header, its expected value and a couple of extra parameters. One optional parameter indicates the desired string comparison mode, and the other is a Boolean that indicates if the comparison is on the entire string. If the negotiator can’t find a match on the formatter using the media type mapping information, it looks at standard HTTP headers such as Accept and Content-Type. If no match is found, it again goes through the list of registered formatters and checks whether the return type of the request can be serialized by one of the formatters.

To add a custom formatter, insert something like the following code in the startup of the application (for example, in the Application_Start method):

config.Formatters.Add(xmlIndex, new NewsXmlFormatter());

Customizing the Negotiation Process

Most of the time, media type mappings let you easily fulfill any special requirements for serialization. However, you can always replace the default content negotiator by writing a derived class and overriding the MatchRequestMediaType method:

protected override MediaTypeFormatterMatch MatchRequestMediaType(
  HttpRequestMessage request, MediaTypeFormatter formatter)

You can create a completely custom content negotiator with a new class that implements the IContentNegotiator interface. Once you have a handmade negotiator, you register it with the Web API runtime:

  new YourOwnNegotiator());

The preceding code usually goes in global.asax or in one of those handy config handlers that Visual Studio creates for you in the ASP.NET MVC Web API project template.

Controlling Content Formatting from the Client

The most common scenario for content negotiation in Web API is when the Accept header is used. This approach makes content formatting completely transparent to your Web API code. The caller sets the Accept header appropriately (for example, to text/xml) and the Web API infrastructure handles it accordingly. The following code shows how to set the Accept header in a jQuery call to a Web API endpoint to get back some XML:

  url: "/api/news/all",
  type: "GET",
  headers: { Accept: "text/xml; charset=utf-8" }

In C# code, you set the Accept header like this:

var client = new HttpClient();
client.Headers.Add("Accept", "text/xml; charset=utf-8");

Any HTTP API in any programming environment lets you set HTTP headers. And if you foresee that you can have callers where this might be an issue, a best practice is to also add a media type mapping so the URL contains all the required information about content formatting.

Bear in mind that the response strictly depends on the structure of the HTTP request. Try requesting a Web API URL from the address bar of Internet Explorer 10 and Chrome. Don’t be surprised to see you get JSON in one case and XML in the other. The default Accept headers might be different in various browsers. In general, if the API will be publicly used by third parties, you should have a URL-based mechanism to select the output format.

Scenarios for Using Web API

Architecturally speaking, Web API is a big step forward. It’s becoming even more important with the recent Open Web Interface for .NET (OWIN) NuGet package (Microsoft.AspNet.Web­­Api.Owin) and Project Katana, which facilitate hosting the API in external apps through a standard set of interfaces. If you’re building solutions other than ASP.NET MVC applications, using Web API is a no-brainer. But what’s the point of using Web API within a Web solution based on ASP.NET MVC?

With plain ASP.NET MVC, you can easily build an HTTP façade without learning new things. You can negotiate content fairly easily with just a bit of code in some controller base class or in any method that needs it (or by creating a negotiated ActionResult). It’s as easy as having an extra parameter in the action method signature, checking it and then serializing the response to XML or JSON accordingly. This solution is practical as long as you limit yourself to using XML or JSON. But if you have more formats to take into account, you’ll probably want to use Web API.

As previously mentioned, Web API can be hosted outside of IIS—for example, in a Windows service. Clearly, if the API lives within an ASP.NET MVC application, you’re bound to IIS. The type of hosting therefore depends on the goals of the API layer you’re creating. If it’s meant to be consumed only by the surrounding ASP.NET MVC site, then you probably don’t need Web API. If your created API layer is really a “service” for exposing the API of some business context, then Web API used within ASP.NET MVC makes good sense.


I wonder if there is away to avoid copying references to objects when you need to create a simple object which has an array of embedded objects.The situation is as follow: I have server which accepts a JSON and applies some logic then stores the object in DB. lets say my form is for saving teams in DB. The server accepts team as json. the team has an array of TeamMember objects, my form has a simple field to enter team member info and add it to team teamMembers array. Now here is the problem, when I add a team member to array list and want to add another team member when I type into the field the added member is changed also !. I know the reason


and it is because I put same reference into the teamMembers array so I have same object added several times. to avoid this I should create a new team member object, copy all teamMember properties and and add it the array.

       var newTeamMember; /*<--- copy teamMember */
       $; /*and add newTeamMember*/

Your question says you want to “avoid deep copy”, but I’m not sure that’s accurate. It sounds like you just want to use angular.copy, because you need to create a copy of the team member and add that to the array:

$scope.addTeamMember = function(teamMember) {
   var newTeamMember = angular.copy(teamMember);
<!doctype html>
<html lang="en">
 <meta charset="UTF-8">
 <title>Example - example-example46-production</title>

 <script src="//"></script>

<body ng-app="copyExample">
 <div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="" /><br />
E-mail: <input type="email" ng-model="" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>

 angular.module('copyExample', [])
 .controller('ExampleController', ['$scope', function($scope) {
 $scope.master= {};

 $scope.update = function(user) {
 // Example with 1 argument
 $scope.master= angular.copy(user);

 $scope.reset = function() {
 // Example with 2 arguments
 angular.copy($scope.master, $scope.user);


Protecting Your Cookies with HttpOnly

Protecting Your Cookies: HttpOnly

Most of the time when you accept input from the user the very first thing you do is pass it through a HTML encoder. So tricksy things like:

<script>alert(‘hello XSS!’);</script>

are automagically converted into their harmless encoded equivalents:

&lt;script&gt;alert(‘hello XSS!’);&lt;/script&gt;

It all starts with this bit of script added to a user’s profile page.

<img src=””<script type=text/javascript

src=””>” /><<img


Through clever construction, the malformed URL just manages to squeak past the sanitizer. The final rendered code, when viewed in the browser, loads and executes a script from that remote server. Here’s what that JavaScript looks like:





That’s right — whoever loads this script-injected user profile page has just unwittingly transmitted their browser cookies to an evil remote server!

As we’ve already established, once someone has your browser cookies for a given website, they essentially have the keys to the kingdom for your identity there. If you don’t believe me, get the Add N Edit cookies extension for Firefox and try it yourself. Log into a website, copy the essential cookie values, then paste them into another browser running on another computer. That’s all it takes. It’s quite an eye opener.

If cookies are so precious, you might find yourself asking why browsers don’t do a better job of protecting their cookies. I know my friend was. Well, there is a way to protect cookies from most malicious JavaScript: HttpOnly cookies.

When you tag a cookie with the HttpOnly flag, it tells the browser that this particular cookie should only be accessed by the server. Any attempt to access the cookie from client script is strictly forbidden. Of course, this presumes you have:

  1. A modern web browser
  2. A browser that actually implements HttpOnly correctly

The good news is that most modern browsers do support the HttpOnly flag: Opera 9.5, Internet Explorer 7, and Firefox 3. I’m not sure if the latest versions of Safari do or not. It’s sort of ironic that the HttpOnly flag was pioneered by Microsoft in hoary old Internet Explorer 6 SP1, a bowser which isn’t exactly known for its iron-clad security record.

Regardless, HttpOnly cookies are a great idea, and properly implemented, make huge classes of common XSS attacks much harder to pull off. Here’s what a cookie looks like with the HttpOnly flag set:

HTTP/1.1 200 OK

Cache-Control: private

Content-Type: text/html; charset=utf-8

Content-Encoding: gzip

Vary: Accept-Encoding

Server: Microsoft-IIS/7.0

Set-Cookie: ASP.NET_SessionId=ig2fac55; path=/; HttpOnly

X-AspNet-Version: 2.0.50727

Set-Cookie: user=t=bfabf0b1c1133a822; path=/; HttpOnly

X-Powered-By: ASP.NET

Date: Tue, 26 Aug 2008 10:51:08 GMT

Content-Length: 2838

This isn’t exactly news; Scott Hanselman wrote about HttpOnly a while ago. I’m not sure he understood the implications, as he was quick to dismiss it as “slowing down the average script kiddie for 15 seconds”. In his defense, this was way back in 2005. A dark, primitive time. Almost pre YouTube.

HttpOnly cookies can in fact be remarkably effective. Here’s what we know:

  • HttpOnly restricts all access to cookiein IE7, Firefox 3, and Opera 9.5 (unsure about Safari)
  • HttpOnly removes cookie information from the response headers in getAllResponseHeaders()in IE7. It should do the same thing in Firefox, but it doesn’t, because there’s a bug.
  • XMLHttpObjectsmay only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.

The big security hole, as alluded to above, is that Firefox (and presumably Opera) allow access to the headers through XMLHttpObject. So you could make a trivial JavaScript call back to the local server, get the headers out of the string, and then post that back to an external domain. Not as easy as document.cookie, but hardly a feat of software engineering.

Even with those caveats, I believe HttpOnly cookies are a huge security win. If I — er, I mean, if my friend — had implemented HttpOnly cookies, it would have totally protected his users from the above exploit!

HttpOnly cookies don’t make you immune from XSS cookie theft, but they raise the bar considerably. It’s practically free, a “set it and forget it” setting that’s bound to become increasingly secure over time as more browsers follow the example of IE7 and implement client-side HttpOnly cookie security correctly. If you develop web applications, or you know anyone who develops web applications, make sure they know about HttpOnly cookies.

article taken from:


<httpCookies domain="String" 
             requireSSL="true|false" />

The following default httpCookies element is not explicitly configured in the machine configuration file or in the root Web.config file, but is the default configuration returned by an application in the .NET Framework version 2.0.

 Internet Explorer added support in Internet Explorer 6 SP1 for a cookie property called HttpOnlyCookies that can help mitigate cross-site scripting threats that result in stolen cookies. When a cookie that has HttpOnlyCookies set to true is received by a compliant browser, it is inaccessible to client-side script. For more information on possible attacks and how this cookie property can help mitigate them, please see Mitigating Cross-Site Scripting with HTTP-Only Cookies tutorial on MSDN.
<httpCookies httpOnlyCookies="false" 
  domain="" />

advantages and disadvantages of using a content delivery network (CDN)

What are the advantages and disadvantages of using a content delivery network (CDN)?

  • The disadvantages may be that it costs money, and it adds a bit of complexity to your deployment procedures.
  • The main advantage is an increase in the speed with which the content is delivered to the users.

When to use a CDN?

  • It will be most effective when you have a popular public website with some type of static content (images, scripts, CSS, etc.).

Is a CDN a performance booster?

  • In general, yes. When a specific request is made by a user, the server closest to that user (in terms of the minimum number of nodes between the server and the user) is dynamically determined. This optimizes the speed with which the content is delivered to that user.


  • It increases the parallelism available.
    (Most browsers will only download 3 or 4 files at a time from any given site.)
  • It increases the chance that there will be a cache-hit.
    (As more sites follow this practice, more users already have the file ready.)
  • It ensures that the payload will be as small as possible.
    (Google can pre-compress the file in a wide array of formats (like GZIP or DEFLATE). This makes the time-to-download very small, because it is super compressed and it isn’t compressed on the fly.)
  • It reduces the amount of bandwidth used by your server.
    (Google is basically offering free bandwidth.)
  • It ensures that the user will get a geographically close response.
    (Google has servers all over the world, further decreasing the latency.)
  • (Optional) They will automatically keep your scripts up to date.
    (If you like to “fly by the seat of your pants,” you can always use the latest version of any script that they offer. These could fix security holes, but generally just break your stuff.)


Web Optimization conditional for browsers

If you have a look into the default format System.Web.Optimization.Scripts.DefaultTagFormat, you will find that you have something like:

<script src='{0}'></script>

So, the only thing you have to do is define a new format. You can do this using the “RenderFormat” method, like:

<%: System.Web.Optimization.Scripts.RenderFormat("<!--[if lt IE 9]><script src='{0}'></script><![endif]-->", "~/bundles/IE9js") %>

 @Scripts.RenderFormat("<!--[if IE 6]><link rel='stylesheet' type='text/css' href='{0}'></link><![endif]-->", "~/bundles/ie6js")
 @Scripts.RenderFormat("<!--[if IE 7]><link rel='stylesheet' type='text/css' href='{0}'></link><![endif]-->", "~/bundles/ie7js")
 @Scripts.RenderFormat("<!--[if IE 8]><link rel='stylesheet' type='text/css' href='{0}'></link><![endif]-->", "~/bundles/ie8js")

Protection against SQL injection

Protection against SQL injection needs to take place on server side, regardless where the incoming call comes from.

Javascript-based sanitation methods are always useless because Javascript runs on client side, and therefore can be forged.

This also applies for AJAX calls: The client doesn’t need to turn JavaScript off; they just need to manipulate the Javascript code they download from your site to fake validation.

CDN in ASP.NET MVC bundling

Once you create ASP.NET MVC project and you looked into the App_start folder BundleConfig.cs file you will fine following code for jQuery bundle.

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

Here you can see that there is a ScriptBundle object created with new. This ScriptBundle object also contains another constructor which also take path of cdn as parameter.

Now let’s first run application without adding CDN and see how its works.


You can see its loaded from bundle not using any CDN there. So Let’s see how we are going to use CDN there. There are lots of CDNs are available there but I’m going to use Microsoft Hosted CDN file in our sample application.

You can find all CDN hosted file on following location.

and here all the jQuery CDN listing for all the versions.

I’m going to use jQuery 1.10.2 version as ASP.NET MVC application by default comes with that version only. Following is a code for that.

bundles.UseCdn = true;
   bundles.Add(new ScriptBundle("~/bundles/jquery",

Here you can see that I have used path without http so that whether you use https or http it will work on both side. Also you can see that I have enabled UseCdn proper to true that will tell bundle to use CDN whenever its available.

As CDN is used in release version, to test application we need to set Debug=”False” in our web.config check that in local machine. So once you are done with that and run in browser you can see in below image its using CDN instead of local file.