REST and WCF connection

后端 未结 6 1008
执笔经年
执笔经年 2021-02-06 15:33

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 pleas

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 15:54

    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:

    
    
    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.

提交回复
热议问题