[From rain marks] restful WCF

Source: Internet
Author: User

Http://www.rainsts.net/article.asp? Id = 651

 

Rest is popular recently ......
WCF 3.5 added support for rest-system. servicemodel. Web.

For me, rest is not used to replace WebService/WCF. It is more of an architectural level than a non-technical level concept and standard. Use the unique resource location URL Uri and the HTTP Request Method to uniquely describe and operate a resource published on the Internet. This brings many benefits:

1. Resource uniqueness

For the following two Uris, the search engine will take them as two different resource crawlers and may be de-duplicated ...... (This is really an annoyance)

Http://www.xxx.com/product/123
Http://www.xxx.com/product/123? OP = Delete

While using rest for expression, then only "http://www.xxx.com/product/123" is the unique address of the resource, we can use the HTTP Method GET request information, use Delete to delete.

GET/product/123 HTTP/1.1
Delete/product/123 HTTP/1.1

2. Better interaction and integration capabilities

Compared with the use of SOAP, WSDL, and WS-* by WCF and WebService, almost all languages and network platforms support HTTP requests. We don't need to implement complex client proxies, and we don't need to use complicated data communication methods to expose our services to anyone who needs them, whether they use VB, Ruby, or Javascript, you can enter HTML form in the address bar of your browser.

This method is external. In terms of internal implementation, we still need to rely on a specific technical solution, including the WCF 3.5 web that we will mention today.

Rest seems simple, but it is not a simple topic. Everyone has their own understanding and usage, and its appearance brings a new hope.

----- Confused split line ---------------

In WCF 3.5, webgetattribute, webinvokeattribute, and uritemplate are introduced to support rest. This allows us to implement restful WCF Service in a simple way.

[Datacontract]
Public class user
{
[Datamember]
Public string name {Get; set ;}

[Datamember]
Public int age {Get; set ;}
}

[Servicecontract]
Public interface imyservice
{
[Operationcontract]
[Webinvoke (uritemplate = "User/{name}/{age}", method = "Post ",
Responseformat = webmessageformat. JSON)]
User createuser (string name, string age );

[Operationcontract]
[Webget (uritemplate = "User/{name}", responseformat = webmessageformat. JSON)]
// [Webinvoke (uritemplate = "User/{name}", method = "get ",
// Responseformat = webmessageformat. JSON)]
User getuser (string name );

[Operationcontract]
[Webinvoke (uritemplate = "User/{name}", method = "delete ",
Responseformat = webmessageformat. JSON)]
String deleteuser (string name );

[Operationcontract]
[Webinvoke (uritemplate = "User/{name}", method = "put ",
Responseformat = webmessageformat. JSON)]
String updateuser (string name );
}

Public class myservice: imyservice
{
Public user getuser (string name)
{
Return new user {name = Name, age = 12 };
}

Public String deleteuser (string name)
{
Return "delete ...";
}

Public user createuser (string name, string age)
{
Return new user {name = Name, age = int. parse (AGE )};
}

Public String updateuser (string name)
{
Return "Update ...";
}
}

Class Program
{
Static void main (string [] ARGs)
{
VaR host = new webservicehost (typeof (myservice), new uri ("http: // localhost: 81 "));
Host. open ();

VaR client = new WebClient ();
Client. headers. Add ("Content-Type", "application/X-WWW-form-urlencoded ");

// Post/getuser/Tom/21 HTTP/1.1
VaR S1 = client. uploadstring ("http: // localhost: 81/user/Tom/21", "Post", String. Empty );
Console. writeline (S1 );

// Get/getuser/ Tom HTTP/1.1
VaR S2 = client. downloadstring ("http: // localhost: 81/user/Tom ");
Console. writeline (S2 );

// Delete/getuser/Tom HTTP/1.1
VaR S3 = client. uploadstring ("http: // localhost: 81/user/Tom", "delete", String. Empty );
Console. writeline (S3 );

// Put/All/Tom HTTP/1.1
VaR S4 = client. uploadstring ("http: // localhost: 81/user/Tom", "put", String. Empty );
Console. writeline (S4 );

Console. writeline ("press any key to exit ...");
Console. readkey (true );
}
}

Output:
{"Age": 21, "name": "Tom "}
{"Age": 12, "name": "Tom "}
"Delete ..."
"Update ..."

Webservicehost is inherited from servicehost and can automatically create required service endpoints (endpoint, webhttpbinding) and other details. Of course, we can still use the original WCF client proxy to call the above service. VaR factory = new webchannelfactory <imyservice> (New uri ("http: // localhost: 81 "));
VaR proxy = factory. createchannel ();
Using (proxy as idisposable)
{
Console. writeline (proxy. createuser ("zhangsan", "23"). Name );
Console. writeline (proxy. deleteuser ("Lisi "));
}

Maybe we will think it is very complicated to create four methods for a resource, so we can do it in the following way, but it is a little troublesome for the WCF client proxy. [Servicecontract]
Public interface imyservice
{
[Operationcontract]
[Webinvoke (uritemplate = "/user/*", method = "*", responseformat = webmessageformat. JSON)]
String user ();
}

Public class myservice: imyservice
{
Public String user ()
{
VaR request = weboperationcontext. Current. incomingrequest;

VaR method = request. method;
VaR ARGs = request. uritemplatematch. wildcardpathsegments;

Switch (method)
{
Case "Post ":
Return "post ...";
Case "delete ":
Return "delete ...";
Case "put ":
Return "Update ...";
Default:
Return "get ...";
}
}
}

Weboperationcontext provides a large number of methods to obtain all request details, or to set the returned information.

Vs2008 provides Ajax-enabled WCF Service. You only need to add a [webget] to the service to implement IIS-host restful WCF Service. [Servicecontract (namespace = "")]
[Aspnetcompatibilityrequirements (requirementsmode = aspnetcompatibilityrequirementsmode. Allowed)]
Public class service1
{
// Add [webget] attribute to use HTTP GET
[Operationcontract]
[Webget (responseformat = webmessageformat. XML)]
Public String Hello (string name)
{
Return "hello" + name;
}
}

Enter "http: // localhost: 1178/service1.svc/Hello?" in the browser? Name = abcxxxxx "to view the call results.

Pay attention to the following points:

1. By default, uritemplate cannot be used. You must comment out "enablewebscript" in the configuration file. <Behavior name = "test. WCF. service1aspnetajaxbehavior">
<! -- <Enablewebscript/> -->
</Behavior>

2. You must add "webservicehostfactory" to. SVC ".

Hello. SVC

<% @ Servicehost Language = "C #" DEBUG = "true" service = "test. WCF. service1 "codebehind =" service1.svc. CS "factory =" system. servicemodel. activation. webservicehostfactory "%>

Let's transform it to support get/post and uritemplate. [Servicecontract (namespace = "")]
[Aspnetcompatibilityrequirements (requirementsmode = aspnetcompatibilityrequirementsmode. Allowed)]
Public class service1
{
[Operationcontract]
[Webinvoke (method = "*", uritemplate = "Hello/{name}", responseformat = webmessageformat. XML)]
Public String Hello (string name)
{
Return "hello" + name;
}
}

OK, in addition to entering "http: // localhost: 1178/service1.svc/Hello/abcooooox" in the browser, we can also use the followingCodeExecute the post action. Client. uploadstring ("http: // localhost: 1178/service1.svc/Hello/xxyyzz", "Post", String. Empty );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.