【文章版权归作者和CNBLOG所有,转载请务必注明原始出处】

猫尾巴的狐狸

导航

WCF4.0新特性-简化配置,WebGet support,Message格式便捷控制,WebFaultException

WCF 的推出整合了.net remoting,webservice 等等,简化了微软平台的通讯开发,可以预计也是微软平台的通讯处理的整合方向。

[简化的配置]

可能都记得,wcf 3.0里面的配置,的确够复杂的;不过这次4.0的发布,微软倒是发布了一些精简的配置办法。

比如我们要Host一个服务,通过下面的简单代码即可,是不是方便了不少?

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled ="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="wsHttpBinding" scheme ="http"/>
    </protocolMapping>
  </system.serviceModel>
</configuration>
----
    WebServiceHost host = new WebServiceHost(typeof(EchoService), new Uri("http://localhost:8080/EchoService"));
            host.Open();
            Console.WriteLine("Press any key to stop this service.");
            Console.ReadKey();
            host.Close();

[WebGet support]

方便的WebGet支持,只需在ServiceContract 里面做少量的更改即可。
比如:
    [ServiceContract]
    public interface IEcho
    {
        [OperationContract, WebGet(UriTemplate = "Echo/{input}")]
        string Echo(string input);
    }
这样你就可以使用 http://serviceaddress/Echo/inputvalue 的方式来访问了。

[返回Message格式控制]

如果您需要返回的数据是Json 或者 text?
1.定义这样的ServiceContract

[OperationContract]
Message GetUser1(string count);

2.实现服务

  public System.ServiceModel.Channels.Message GetUser1(string count)
        {
            List<UserInfo> result = GetUser(count);
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
            return WebOperationContext.Current.CreateJsonResponse<List<UserInfo>>(result);
        }

这里便返回Json的格式了。当然,还有其他格式的便捷支持.

image

[WebFaultException]
您可以方便的抛出这样的错误,浏览器端将收到 Http 400 bad request的信息。

 throw new WebFaultException<string>("format Error", System.Net.HttpStatusCode.BadRequest);

posted on 2010-05-04 12:14  GinoHuo  阅读(693)  评论(1编辑  收藏  举报