加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

RESTful WCF

发布时间:2020-12-17 02:36:31 所属栏目:安全 来源:网络整理
导读:相较 WCF、WebService 使用 SOAP、WSDL、WS-* 而言,几乎所有的语言和网络平台都支持 HTTP 请求。我们无需去实现复杂的客户端代理,无需使用复杂的数据通讯方式既可以将我们的服务暴露给任何需要的人,无论他使用 VB、Ruby、JavaScript,甚至是 HTML FORM,

相较 WCF、WebService 使用 SOAP、WSDL、WS-* 而言,几乎所有的语言和网络平台都支持 HTTP 请求。我们无需去实现复杂的客户端代理,无需使用复杂的数据通讯方式既可以将我们的服务暴露给任何需要的人,无论他使用 VB、Ruby、JavaScript,甚至是 HTML FORM,或者直接在浏览器地址栏输入。

WCF 3.5 引入了 WebGetAttribute、WebInvokeAttribute、UriTemplate 来增加对 REST 的支持,这使得我们用很简单的方式就可以实现 RESTful WCF Service。

可参考以下几篇文章:

《深入浅出REST》 : 作者 Stefan Tilkov译者 苑永凯

《Web 编程模型》 : MSDN文档
《使用 WCF 和 .NET Framework 3.5 进行 HTTP 编程》 : Justin Smith

《Twitter WCF Client》

下面我们来看一个简单的例子:

[ServiceContract]
public interface IService
{
???? [OperationContract]
???? [WebGet]
???? string EchoWithGet(string s);

???? [OperationContract]
???? [WebInvoke]
???? string EchoWithPost(string s);
}

?

public class Service : IService
??? {
??????? public string EchoWithGet(string s)
??????? {
??????????? return "You said " + s;
??????? }

??????? public string EchoWithPost(string s)
??????? {
??????????? return "You said " + s;
??????? }
??? }

?

static void Main(string[] args)
?????? {
?????????? AppDomain.CreateDomain("Server").DoCallBack(delegate
?????????? {
?????????????? ServiceHost host = new ServiceHost(typeof(Service),new Uri("http://localhost:8020"));
?????????????? host.AddServiceEndpoint(typeof(IService),new BasicHttpBinding(),"Soap");
?????????????? ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService),new WebHttpBinding(),"Web");
?????????????? endpoint.Behaviors.Add(new WebHttpBehavior());

?????????????? host.Open();
?????????? });
?????????? using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8020/Web")))
?????????? {
?????????????? IService channel = wcf.CreateChannel();

?????????????? string s;

?????????????? Console.WriteLine("Calling EchoWithGet by HTTP GET: ");
?????????????? s = channel.EchoWithGet("Hello,world");
?????????????? Console.WriteLine("?? Output: {0}",s);

?????????????? Console.WriteLine("");
?????????????? Console.WriteLine("This can also be accomplished by navigating to");
?????????????? Console.WriteLine("http://localhost:8020/EchoWithGet?s=Hello,world!");
?????????????? Console.WriteLine("in a web browser while this sample is running.");

?????????????? Console.WriteLine("");

?????????????? Console.WriteLine("Calling EchoWithPost by HTTP POST: ");?????????????? s = channel.EchoWithPost("Hello,world");?????????????? Console.WriteLine("?? Output: {0}",s);?????????? }?????????? Console.ReadLine();?????? }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读