By Ugo Lattanzi on . th , 2014 in webapi | comments

With the latest version of ASP.NET Web API, Microsoft introduced support for cross domain requests, usually called CORS (Cross-Origin Resource Sharing)

By default it's not possible to make HTTP requests using Javascript from a source domain that is different from the called endpoint. For example, this means that it's not possible to call the URL from a domain

This limitation has been introduced for security reasons: in fact, without this protection, a malicious javascript code could get info from another site without noticing the user.

However, even if the reason of this limitation is clear, sometimes we need to call anway something that is not hosted in our site. The first solution is is to use JSONP. This approach is easy to use and it's supported by all browsers; the only problem is that the only HTTP VERB supported is GET, which has a limitation on the lenght of the string that can be passed as query parameter.

Otherwise, if you need to send lot of information we can't use this way, so the soulution could be to "proxy" the request locally and forward the data server side or to use CORS.

Basically CORS communication allow you to overtake the problem by defining some rules that makes the request more "secure". Of course the first thing we need is a browser that support CORS: fortunately all the latest browsers support it. Anyway, we have to consider that, looking at the real world, there are several clients that are still using Internet Explorer 8 which, among other things, doesn't support CORS.

The following table ( shows which browsers offer CORS support.


there are several workaround that allows you to use CORS with IE8/9 but there are some limitations with the VERBS (more info here)

Now that it's clear what is CORS, it's time to configure it using one of the following browsers:

  • Internet Explorer 10/11
  • Chrome (all versions)
  • Firefox 3.5+
  • Safari 4.x

Now we need two different project, one for the client application and another one for the server, both hosted in different domains (in my esamply I used Azure Web Sites, so I've for the server and for the client)


Server Application

Once the project has been created, it's important to enable CORS for our "trusted" domains, in my sample

If you used the default Visual Studio 2013 template, your Global.asax.cs should look like this:

Next, it's time to edit the file with the API configuration, "WebApiConfig.cs" into "App_Start".

N.B.: Before editing the file it's important to install the right NuGet Package; the default template included with Visual Studio doesn't have CORS package, so you have to install it manually.

PM> Install-Package Microsoft.AspNet.WebApi.Cors

Once all the "ingredients" are ready, it's time to enable CORS:

Our API Controller looks like this:

The most important part of this code is EnableCors method and the namesake attribute (included the VERBS, Domain and HEADERS)

In case you don't want to completely "open" the controller to CORS requests, you can use the single attribute in the Action or leave the attribute in the controller and apply the DisableCors attribute to the actions you want to "close"

Client Application

At this time, the server is ready, it's time to work client side.

The code we'll see for the client is just plain Javascript, so you can use a simple .html page without any server side code.

The HTML Code:

Javascript Code:

If you did everything right, you can to deploy our apps (server and client) to test them.


When you click on the "Test It now" button the result should look like this:


Otherwise if something goes wrong, check the point above.


How does it work

CORS is a simple "check" based on HEADERS between the caller and the server.

The browser (client) adds the current domain into the hader of the request using the key Origin.

The server check that this value matches with the allowed domains specified in the attribute, answering with another HEADER information named Access-Control-Allow-Origin

If both keys have the same values, you have the data, otherwise you'll get an error.

The screenshot below shows the headers:


Here is, instead, the classic error in case the HEADERS doesn't match:




For me that I love to sperate the application using an API layer, CORS is absolutely cool. The onyl downside is that it's not supported by all the browser. Let's just hope that hope that all the IE8/9 installations will be replaced soon :-)

The demo is available here

By Ugo Lattanzi on . th , 2014 in aspnetmvc | comments

One pillar of ASP.NET MVC is the extensibility. It means you can add whatever you want wherever you want (or something like that).

Like all frameworks, ASP.NET MVC does not cover all features requested by developers, but offers the opportunity to create your own logic. That means extensibility.

In my case, the goal was to render a partial view into a JavaScript file.

Before to see how you can do that, it’s important to understand what does really mean “render a partial view into a Javascript file”.

In this example I want to create a simple HTML including the base info for a user profile (Firstname, Lastname and website).

The HTML Looks like this.

Render that HTML into a JavaScript means encoding everything and putting it into a document write. The result should looks like this.

In MVC all requests need a Controller and an Action, which must return something that could be an HTML, json or javascript (in my case).

To do this, the first thing to do is create a JavascriptResult (and his extension method) like that:

As you can see the code is really simple, I render the partial into a string, encode the content and return it changing the content type.

Now you are able to use the following code:

The last thing to do is to render the partial view into another site, so you have to include your JavaScript like a normal resource.

In the screenshot below you can see how a client site (not the site that hosts the controller) shows the partial.



What is cool about that approach is about server side technology. Because we are returning a Javascript file the client could be a simple .html static page or something generated with nodejs or whatever you want.

Is it cool?

The code is available here

By Ugo Lattanzi on . th , 2013 in .net webdev | comments

ASP.NET_Web_API_Succinctly_download In the past week, my friend Emanuele Del Bono (Ema for all people who know him) announced his first tech book about ASP.NET Web API.

Who follow me knows that I’m a HTTP addicted, so I love everything around web development, starting from websites but also including APIs, especially if developed using WEB API (I wrote several posts about that framework).

Syncfusion published the book in the usual (cool IMHO) format: a free, small e –book (it’s just 90 pages).

Personally, I am not a fan of big books, especially if they are tech book. The reason is pretty simple: I don’t have so much time to read so, when I completed the chapter number 15 of a book with 800 pages, probably the arguments/frameworks of the book are already out of date.

About the author I can’t spend so much words, Ema is a cooler and smart developer and he was a speaker when I participate for the first time to a conference as attendee (don’t remember the year, but was about localization in C# and he showed an application with “Bresciano”, strange Italian dialect :-)).

The table of content includes all you need to start with Web API:

  1. About REST
  2. Hello Web API
  3. The Life of a Request
  4. The Routing System
  5. The Controller
  6. Model Validation
  7. Content Negotiation
  8. Message Handlers
  9. Security
  10. OData
  11. Hosting
  12. Testing
  13. Appendix A: HTTP Status Codes
If you need more detail, of course there are several cool blog posts around the web, but I suggest to keep in touch with that blog (is an aggregate of the cooler Web API Bloggers, included me :D).

What’s next? Start read this super cool book downloading it from here.

By Ugo Lattanzi on . th , 2013 in .net azure | comments

In the last few weeks, I worked about some APIs using ASPNET Web Api and, for the data storage, Entity Framework and Sql Server; everything hosted on Azure.

Nothing sensational! make a rest call, read the data and return a json. The only new thing (for me) was the Spatial Data.

Thinking about this great post by Scott Hanselman, in this case I chose to be a Googler :D so, I started to learn Spatial Data with Entity Framework from this post by Rick Strahl.

Such as all posts by Rick, also this one is awesome. It explains very well all you need to start with Spatial Data and everything worked right at first try.

So, where is the reason of this post? The deploy. In my local environment, I was able to execute all Spatial Queries but, in the production environment, Iwas getting this strange message “The method or operation is not implemented.” In this line of code:

Keep looking on Google I found the reason. DefaultSpatialServices in Entity Framework are using SqlGeography and SqlGeometry types as backing types. These are a part of Microsoft.SqlServer.Types.dll that is not included in the .NET Framework.

On my local installation it works because I've installed SQL Server and it register that assembly into the GAC (Global Assembly Cache) during the setup procedure. Fortunately Azure Web Site and Cloud Service don't have Sql Server installed so the assembly is missing.

The solution is to copy the assembly directly in your bin folder.

Now, where is the assembly located?

Not easy to find, anyway it’s here C:Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies

Stay Tuned!

By Ugo Lattanzi on . th , 2013 in .net | comments

What I really appreciate in ASP.NET MVC and WebAPI are the binders and its validation. It’s really cool to have a class with all parameter and, for those who have the data annotations, the automatic validation.

In this article, I’m going to “speak” about the validation, probably one of the most boring stuff a developer needs do during the programming.

That’s what I mean with “boring stuff”

As you can see in the method above there are four parameters and I need to validate three of them before starting to do anything (in the example website is validated only if it has a value). Probably you, and also me, wrote this code thousand and thousand times …. ok It’s time to remove that.

My idea is to use the Data Annotation Attributes for the parameters and, using the AOP (Aspect Oriented Programming) and Interceptor Pattern, run automatically the validation for all ours layer.

Probably all of you use a Dependency Injection Framework (if you don’t use it, you have to) like Castle Windsor, Ninject, Unity and so on. All of these offers the opportunity to inject some code before calling a method for a registered service (Interceptor Pattern). In my example I’m using Castle (I love it), but the code it’s easy to move to another framework.

Stop speaking and let’s start coding.

The first thing to do is to understand how to run manually the validation: K. Scott Allen wrote a good article here, so I’m starting from this.

Now we have to create a container class for all the parameters and to add the Data Annotations. That’s important because we can’t use the Data Annotations directly on the parameter. If you did everything correct, your class now should looks like this:

Because a method could have more than one parameter, and we don’t really need to validate all of these, it could be important to tell to the validation service (our interceptor) what needs to be validated and what doesn’t. For this reason I’ve created a custom attribute, ValidateAttribute:

No comments for this code, it is used only like a marker.

Now change the signature of your method using the attribute and the input class like this:

Good, everything is ready except for the interceptor, it’s time to create it:

The interceptor logic is really simple. It iterates all parameters and, only for these who have my custom attribute, it calls the Validate method.

To use an interceptor is important to register it and add to your service:

That’s all, run the this code to have the validation:

From now, every time you call the method CreateUser (resolved by Castle), the validation will be automatically raised and, for the parameter with a wrong value, an ImperugoValidationExcpetion will throw, you can catch them and choose how to show the message.

It’s not finished yet :). If you prefer, I’ve created a NuGet Package that helps to reduce the code. There are two packages:

  1. Imperugo.Validation
  2. Imperugo.Validation.Castle
The first one contains only the necessary stuff to create the right interceptor; the second one is the Castle implementation (soon I’ll release also a package for Ninject, Unity and so on).

The first thing to do is to install the package (Castle in this case):


Now change the Castle code like this:

If you use a different Framework and you like this validation, fork the repo here, add the new Framework, and create a “pull request”.

All my code is available here.

I’m working on the next release that is really faster because include a cache strategy, so stay tuned.