2005/12/01

.net webservice 概览 阅读asp.net的QuickStart

好久没有看web Service了 所以到 asp.net 上找篇文档看看
1、定义WebService
2、WS-I Basic Profile 1.1 支持
3、禁用压缩
4、使用Session
5、Schema 验证
6、service的异步调用
7、客户端调用时动态配置WebService的url
8、在Service中抛出SOAP的异常
9、使用SOAP Headers 添加附加信息(如:身份信息)
10、使用默认的网络身份验证

1、定义WebService
页面上
  使用WebService命令指定页面的类型为WebService和实现Service的类
  <%@ WebService Language="C#" CodeBehind="~/App_Code/BaseOne.cs" Class="BaseOne" %>
类定义
  使用WebService属性表示定义的Service Class
  [WebService(Namespace = "http://test.com/webservice")]
  使用WebMethod属性定义Service 方法
  [WebMethod(Description="test description!",MessageName="HelloWorld2")]

2、WS-I Basic Profile 1.1  支持
asp.net 2.0 实现了对 WS-I Basic Profile 1.1 Conformance 的支持,只需要在service class上使用WebServiceBinding 属性标示一下就可以了,虽然看了一会那个BP1.1也没看到什么所以然
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1, EmitConformanceClaims=true)]

3、禁用压缩
在客户端使用代理时设置
EnableDecompressionService service = new EnableDecompressionService();
service.EnableDecompression = true;
4、使用Session
//On the client you must add the following code (for session state only):
serviceName.CookieContainer = new System.Net.CookieContainer();
//Setting EnableSession to true allows state to be persisted per Session
   [WebMethod(EnableSession=true)]
   public String UpdateSessionHitCounter() {
      //update the session "HitCounter" here
      return Session["HitCounter"].ToString();
   }
5、Schema 验证
//create the validating reader
XmlTextReader tr = new XmlTextReader(input, XmlNodeType.Document, null);
XmlValidatingReader vr = new XmlValidatingReader(tr);

//add the schema and set the validation type to schema
XmlSchemaCollection schemas = new XmlSchemaCollection();
schemas.Add("Microsoft.Samples.Web.Services", "insert location here...");
vr.Schemas.Add(schemas);
vr.ValidationType = ValidationType.Schema;

//add our event callback function to the event handler in case there is a validation error
vr.ValidationEventHandler += new ValidationEventHandler (ValidationHandler);

try
{
    //if there is an error we will fall out of this while loop and our callback function will be called
    while (vr.Read())
    {
        //do nothing 
    }
}
catch (Exception exception)
{
    //an exception will be thrown if there are non-validation errors, e.g. in the case of malformed XML
}
6、service的异步调用
//First implement the HelloWorldCompleted method using the following signature:
//public void HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs args)

//Create the Web service
HelloWorldWaitService service = new HelloWorldWaitService();
//Add our callback function to the event handler
service.HelloWorldCompleted += this.HelloWorldCompleted;
//Call the Web service asynchronously
service.HelloWorldAsync("first call");
//when the Web service call returns the HelloWorldCompleted method will be called
7、客户端调用时动态配置WebService的url
<configuration>
   <appSettings>
      <add key="WSUrl" value="insert location here..." />
   </appSettings>
</configuration>
HelloWorldService service = new HelloWorldService();
//Change the location of the Web service in machine.config if desired
service.Url = System.Configuration.ConfigurationSettings.AppSettings["WSUrl"];
output.Text = service.HelloWorld();
8、在Service中抛出SOAP的异常
//assume that there was an error validating the SOAP Message
if(true)
{
    XmlDocument doc = new XmlDocument();
    //insert your own XML into the XmlDocument,
    //this will go into the Detail element of the SOAP fault
    string errorMsg = "An error was received...";
    //the SOAP fault will contain a human-readable error message,
    //the fault code, the SOAP actor, and the detail element   
    SoapException exc = new SoapException(errorMsg, SoapException.ClientFaultCode, "", detail);
    throw exc;
}
9、使用SOAP Headers 添加附加信息(如:身份信息)
客户端调用
// On the server, create the AuthHeader class which extends from SoapHeader
public class AuthHeader : SoapHeader {
    public string Username;
    public string Password;
}
  
// On the client, create a new instance of the AuthHeader class
AuthHeader myHeader = new AuthHeader();

//WARNING: This sample is for demonstration purposes only.  Username/password information is sent in plain text,
//which should never be done in a real application. It is not secure without modification. 
myHeader.Username = "JaneDoe";
myHeader.Password = "password";

// Set the AuthHeader public member of the Web service instance to myHeader
service.AuthHeaderValue = myHeader;
   
// Call the Web service, which automatically sends the header with the request
string answer = service.HelloWorld();
服务器端接收
// AuthHeader class extends from SoapHeader
    public class AuthHeader : SoapHeader {
        public string Username;
        public string Password;
    }

    [WebService(Description="Simple sample to demonstrate use of SOAP Headers", Namespace="Microsoft.Samples.XmlMessaging.WebServices")]
    public class HeaderService {

        public AuthHeader sHeader;

        [WebMethod(Description="This method requires a custom soap header set by the caller")]
        [SoapHeader("sHeader")]
        public string SecureMethod() {

            if (sHeader == null)
              return "ERROR: Please supply credentials";

            string usr = sHeader.Username;
            string pwd = sHeader.Password;

            if (AuthenticateUser(usr, pwd)) {
                 return "SUCCESS: " + usr;
            }
            else {
                 return "ERROR: Could not authenticate";
            }
        }

        private bool AuthenticateUser(string usr, string pwd) {

            if ((usr != null)&&(pwd != null)) {
                // could query a database here for credentials...
                return true;
             }
            return false;
        }
    }
10、使用默认的网络身份验证
UseDefaultCredentialsService service = new UseDefaultCredentialsService();
service.UseDefaultCredentials = true;

没有评论: