开发者

REST and WCF connection

I am specifically looking for an example which use a) WCF & REST. After a long googling, though I got some but they are beyond my understanding.

Could some one please give me a very simple example say "Hallow World" or Summation of 2 numbers which will 开发者_C百科give me a clear insight about how to write a server, and also how to consume the same from the client end.

Also if any good link that explains this kind of example in simple terms kindly tell me that.

Thanks


REST in WCF is not that hard once you figure it out.

First you must define your interface.

Here is an example.

[ServiceContract]
public interface IRESTExample
{
    [WebGet(UriTemplate = "interaction/queue?s={site}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string QueueInteraction(string site);

    [WebGet(UriTemplate = "interaction/cancel?id={interactionId}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string CancelInteraction(string interactionId);

    [WebGet(UriTemplate = "queue/state?s={site}&q={queue}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string QueueState(string site, string queue);

}

You can see in the WebGet you define the final URL. So it depends on where you bind it, but say you bind the endpoint to www.example.com/rest

QueueInteraciton would be www.example.com/rest/interaction/queue?s=SomeSite

Where {stie} or {parameterName} is replaced with the name of the parameter.

The implemetion is just a simple class, I am going to assume you know how to implement an interface. If you need help just leave a comment.

Now binding the endpoint. In the end it is not that hard, you can do it all in the config.

<system.serviceModel>
    <services>
        <service name="Stackoverflow.Example.Service.RestExample" behaviorConfiguration="MyServiceTypeBehaviors">
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:2136/RestExample"/>
                </baseAddresses>
            </host>

            <endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="xmlBehavior" contract="Stackoverflow.Example.Service.IRESTExample" />

        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="MyServiceTypeBehaviors" >
                <!-- Add the following element to your service behavior configuration. -->
                <serviceMetadata httpGetEnabled="true" />
            </behavior>
        </serviceBehaviors>

        <endpointBehaviors>
            <behavior name="jsonBehavior">
                <webHttp/>
            </behavior>
            <behavior name="xmlBehavior">
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <bindings>
        <basicHttpBinding>
            <binding name = "NoSecurity">
                <security mode = "None" />
            </binding>
        </basicHttpBinding>
    </bindings>
</system.serviceModel>

Now the code to start the service and bind it. YOu can do it in anything, for example a console app.

RestExample exampleService = new RestExample();

host = new ServiceHost(exampleService);

host.Open();

This should be enough to get started.


msdn article An Introduction To RESTful Services With WCF with code example at msdn code gallery. Also check out this codeproject article


David Basarab's response is correct, but there's a much simpler way to do this without all the manual wire-up. Especially if you've used to classic ASMX web services and don't have a lot of WCF experience, the following method is dirt simple.

  1. In a Visual Studio 2010 web project, add a reference to System.ServiceModel.Web.
  2. Chose "add new item" in your project. The template you want is in "Web" and is called "AJAX-enabled WCF Service". Don't choose the vanilla "WCF Service"! If you do you have to do all the web.config wiring yourself that David Basarab described, and it's a pain. The "AJAX-enabled WCF Service" does all that setup for you. Name your service whatever you want.
  3. Open up the .svc file. In the [ServiceContract] attribute on your class, fill in the Namespace string parameter with whatever you want.
  4. You'll get a sample DoWork() method and a bunch of comments telling you what to do in the file. The trick to getting the RESTful API is to add [WebGet()] attributes to your web methods. Add one to DoWork() and verify everything functions for you.

So, to call the DoWork() method, you'd hit this in your browser: http://localhost/MyAjaxEnabledService.svc/DoWork

Let's add a new HelloWorld() method now that shows some parameters and output.

VB:

<OperationContract()>
<WebGet(ResponseFormat:=WebMessageFormat.Xml)>
Public Function HelloWorld(ByVal name As String) As String
    WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"
    Return String.Format("Hello, {0}!", If(String.IsNullOrWhiteSpace(name), "world", name))
End Function

C#:

[OperationContract()]
[WebGet(ResponseFormat=WebMessageFormat.Xml)]
public string HelloWorld(String name) {
    WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
    Return String.Format("Hello, {0}!", String.IsNullOrWhiteSpace(name) ? "world" : name);
}

Now you can visit:

http://localhost/MyAjaxEnabledService.svc/HelloWorld?name=MattMc3

There's a lot of crappy and confusing documentation out there about WCF, especially for those who crave the simplicity of the old .ASMX style. Hopefully this helps someone get started with WCF. There's a lot more you can do with it than the old ASMX-style, but it's hard to ramp up and not get discouraged with MS for their poor help with the transition from ASMX. You can read more about quick-and-dirty RESTful WCF services here.


If you really want to do ReST then use a web framework that will lead you down the right path. See OpenRasta.

It is not impossible to do WCF to do ReST, it is just very difficult to learn how to do Rest with a framework that will frequently get in your way and lead you in the wrong direction.


In Microsoft Web Developer, you can use the Online Template "WCF REST Service." It will set up a project for you with the correct web.config and global.asax files.


You can create an WCF REST web service by configuring your endpoint to use a webHttpBinding as seen in this in-depth tutorial:

http://www.west-wind.com/weblog/posts/310747.aspx

Here is another open source web services framework that simplifies creating XML and JSON REST web services without requiring any extra configuration.

Edit: Added link to good article articulating the spirit of REST:

http://tomayko.com/writings/rest-to-my-wife

Link to blog post comment explaining common misconceptions of REST:

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜