Geeks With Blogs
AngelEyes on .Net Tips, tricks and WTFs about Asp .Net, SQL Server and the likes.

 

A simple and straight forward article taken from http://christopherdeweese.com/blog2/post/drop-the-soap-wcf-rest-and-pretty-uris-in-net-4 which uses WCF REST Service Template 40(CS) 



Drop the Soap: WCF, REST, and Pretty URIs in .NET 4
Years ago I was working in libraries when the Web 2.0 revolution began.  One of the things that caught my attention about early start-ups using the AJAX/REST/Web 2.0 model was how nice the URIs were for their applications.  Those were my first impressions of REST; pretty URIs.  Turns out there is a little more to it than that.

REST is an architectural style that focuses on resources and structured ways to access those resources via the web.  REST evolved as an “anti-SOAP” movement, driven by developers who did not want to deal with all the complexity SOAP introduces (which is al lot when you don’t have frameworks hiding it all).  One of the biggest benefits to REST is that browsers can talk to rest services directly because REST works using URIs, QueryStrings, Cookies, SSL, and all those HTTP verbs that we don’t have to think about anymore.

If you are familiar with ASP.NET MVC then you have been exposed to rest at some level.  MVC is relies heavily on routing to generate consistent and clean URIs.  REST for WCF gives you the same type of feel for your services.  Let’s dive in.

WCF REST in .NET 3.5 SP1 and .NET 4
This post will cover WCF REST in .NET 4 which drew heavily from the REST Starter Kit and community feedback.  There is basic REST support in .NET 3.5 SP1 and you can also grab the REST Starter Kit to enable some of the features you’ll find in .NET 4.

This post will cover REST in .NET 4 and Visual Studio 2010.

Getting Started
To get started we’ll create a basic WCF Rest Service Application using the new on-line templates option in VS 2010:



When you first install a template you are prompted with this dialog:



Dude Where’s my .Svc File?
The WCF REST template shows us the new way we can simply build services.  Before we talk about what’s there, let’s look at what is not there:

The .Svc File
An Interface Contract
Dozens of lines of configuration that you have to change to make your service work
REST in .NET 4 is greatly simplified and leverages the Web Routing capabilities used in ASP.NET MVC and other parts of the web frameworks.  With REST in .NET 4 you use a global.asax to set the route to your service using the new ServiceRoute class.  From there, the WCF runtime handles dispatching service calls to the methods based on the Uri Templates.

global.asax

using System;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Routing;

namespace Blog.WcfRest.TimeService
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes();
        }

        private static void RegisterRoutes()
        {
            RouteTable.Routes.Add(new ServiceRoute("TimeService",
                new WebServiceHostFactory(), typeof(TimeService)));
        }
    }
}

The web.config contains some new structures to support a configuration free deployment.  Note that this is the default config generated with the template.  I did not make any changes to web.config.

web.config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,
           System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
      <webHttpEndpoint>
        <!--
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
            via the attributes on the <standardEndpoint> element below
        -->
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

</configuration>


Building the Time Service
We’ll create a simple “TimeService” that will return the current time.  Let’s start with the following code:

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace Blog.WcfRest.TimeService
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class TimeService
    {
        [WebGet(UriTemplate = "CurrentTime")]
        public string CurrentTime()
        {
            return DateTime.Now.ToString();
        }
    }
}
The endpoint for this service will be http://[machinename]:[port]/TimeService.  To get the current time http://[machinename]:[port]/TimeService/CurrentTime will do the trick.

The Results Are In


Remember That Route In global.asax?
Turns out it is pretty important.  When you set the route name, that defines the resource name starting after the host portion of the Uri.



Help Pages in WCF 4
Another feature that came from the starter kit are the help pages.  To access the help pages simply append Help to the end of the service’s base Uri.





Dropping the Soap
Having dabbled with REST in the past and after using Soap for the last few years, the WCF 4 REST support is certainly refreshing.  I’m currently working on some REST implementations in .NET 3.5 and VS 2008 and am looking forward to working on REST in .NET 4 and VS 2010.

Posted on Sunday, December 5, 2010 10:39 AM | Back to top


Comments on this post: WCF REST on .Net 4.0

# re: WCF REST on .Net 4.0
Requesting Gravatar...
really nice! keep it up man
Left by Hi on Feb 12, 2011 10:46 PM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
thanks you. this share is prefect.
Left by eca on Apr 01, 2011 10:15 AM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
very nice shared.
thanks you.
Left by eca on Apr 29, 2011 2:52 PM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
Thanks. Nice site for begginers like me .
Left by Shambhavi on Jun 20, 2011 4:11 PM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
very nice shared. thanks you for this share
Left by eca on Jul 15, 2011 11:38 AM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
I am facing problem in using the wcf rest based service in my project.
after deploye wcf service on server, when calling it in a html page using jquery, I are getting "Access Denied" (jquery 1.4.2.min.js) or "No Transport" (jquery 1.7.2.min.js)

Please let me know /assist how to resolve this.
I have allready tried: jsonp but issue is still there.
Left by Anil on Jul 24, 2012 11:49 AM

# @Anil
Requesting Gravatar...
Did you check manually, without JS, if the service works?
Left by Angel Eyes on Jul 29, 2012 12:25 PM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
Please let me know, can we able to develop with out using Starter kit for WCF REST.
Left by Srinivasulu P on Jan 08, 2013 11:34 AM

# re: @Srinivasulu P
Requesting Gravatar...
I don't understand that question. Why wouldn't you be able to develop without the starter kit?
Left by angeleyeschina on Jan 08, 2013 2:44 PM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
Post is very good.

Dont mind me asking this question,I have recently started working with RESTful services..

I have gone thru some sites on this but i dont get the clear picture still..(scalability,security,reduce latency..etc)

1.Would like to know advantages and disadvantages of rest services..please dont mind but can u please be more explanatory on it?
2.Also, how exactly this endpoint for each service method be helpful in implementing REST service.

Thanks a lot in advance

Sorry!!!! if this question bores you
Left by Sateesh on May 22, 2013 9:32 AM

# re: Sateesh
Requesting Gravatar...
I'm not sure I understand your questions...

1. Maybe you should read http://stackoverflow.com/a/209945/532517 REST is simpler to use, after you make the services. It's easier to understand and test, with a browser, for example.
2. What do you mean? the endpoint is the URL at which the service replies to 'queries'. Without it, you cannot access the service.
Left by angel eyes on May 22, 2013 11:48 PM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
Thank you very much for the link it is very helpfu for me.

But one small doubt i have is that (not sure if it annoys you!! :-) )

If my understanding is correct in WCF we have multiple operation contracts within as service contract having defined and a single end point for the entire service....

My question is that

when it comes to RESTful..we have Service contract and within which we have operation contracts but having attributed with webInvoke,webGet..., having Uri template path(which is considered as part of endpoint) defined for each operation contract.Why for each operation contract we have URitemplate path and whats the use or advantage defining like this?

Really sorry...having half and half info..reason why i might be confusing :-(

Tryin to sort things out from my end as well.

Thanks a lot for ur response and taking time for reading this.
Left by Sateesh on May 23, 2013 9:32 AM

# re: Sateesh
Requesting Gravatar...
The Uri Template is there to help you create and reuse easy to read (& hack) URIs. The webInvoke,webGet specify the type of http request. This is fundamental to the REST idea. Every URI specifies a resource (think: UriTemplate) . When you access that resource, you need to specify what you want to do with it - add it? update it? delete it? that's where the attributes are helpful.

I recommend reading http://www.looah.com/source/view/2284
Left by angel eyes on May 23, 2013 6:21 PM

# re: WCF REST on .Net 4.0
Requesting Gravatar...
can some buddy told me that how to consume rest full service with out uritemplae, please provide me the solution if any buddy have.
thanks in advance....
Left by narendra singh solanki on Feb 22, 2014 2:17 PM

Your comment:
 (will show your gravatar)


Copyright © AngelEyes | Powered by: GeeksWithBlogs.net