Вы находитесь на странице: 1из 27

Creating ASP.

NET Web Services

申丽萍 Shen Liping


Shen-lp@cs.sjtu.edu.cn

ftp.cs.sjtu.edu.cn/shen-lp/dotnet/
Contents
‡ Creating an ASP.NET Web Services
‡ WSDL Tool
‡ Proxy Class
‡ Stateful Web Service
‡ ASP.Net1.0 vs. ASP.Net2.0
‡ Final Project

2008-4-21
Creating an ASP.NET Web Services

‡ A Web service is defined by an .asmx file, which


serves as the endpoint for the Web service ASP .Net
‡ The implementation of the Web service is
encapsulated within a class which inherits from
System.Web.Services.WebService class. The class
definition can either appear inline within the .asmx file
or be contained in a separate dynamic link library
(DLL).
‡ .asmx page uses @WebService directive to contain
information that the runtime can use to locate the class.
‡ Each method that is intended to be exposed by the
Web service must be public and must be decorated
with the WebMethod attribute.
2008-4-21
Sample Web Service

<%@WebService Language=“C#“ Class=“MyClass“ %>

using System.Web.Services;

public class MyClass : WebServices


{
[ WebMethod ]
public int Compute1(int i1, int i2)
{
return i1 + i2;
}

public int Compute2(int i1, int i2)


{
if (i1 > i2) return i1 - i2;
else return i2 - i1;
}
}
2008-4-21
Web Services
Programatic use

WSDL
Courseware.asmx?WSDL

Service Definition(XML)

Proxy
Proxy
DLL
.ASMX
.ASMX
DLL

2008-4-21
@ WebService Directive
Defines XML Web service specific (.asmx file) attributes used
by the ASP.NET parser and compiler.
<%@ WebService attribute="value" [attribute="value"…] %>

Attributes:
• Language: Specifies the language used when compiling all inline code within
the XML Web service file (.asmx).
• CodeBehind :Specifies the source file implementing the XML Web service,
when the class implementing the XML Web service does not reside in the same
file and has not been compiled into an assembly and placed in the \Bin directory.
• Class : Specifies the class implementing the XML Web service that is
automatically compiled the first time the XML Web service is accessed after
changes.
• Debug : Indicates whether the XML Web service should be compiled with
debug symbols
2008-4-21
@ Assembly Directive
Links an assembly to the current page during compilation,
making all the assembly's classes and interfaces available for
use on the page.

<%@ Assembly Name="assemblyname" %> or


<%@ Assembly Src="pathname" %>

Name: The name of the assembly to link to the XML Web service.
Src: The path to a source file to dynamically compile and link against.
Note The path to the assembly or source file in an @ Assembly
directive must be a relative path to the Web application hosting the
XML Web service.

2008-4-21
WebMethod Attribute

2008-4-21
WebService Attribute

The ASP.NET page framework also provides the WebService


attribute. This attribute is set at the class level and is used to
modify properties of the Web service as a whole. Changes
made via the WebService attribute will be reflected in the
Web service's WSDL document.

2008-4-21
Transport Protocols and Bindings
‡ By default the Web services supports three styles of binding to
the HTTP protocol: SOAP, HTTP GET, and HTTP POST which is
defined in the machine.config file
‡ You can easily specify which protocol bindings your Web service
will support in the web.config file, which locates within the root
directory of the Web application
<system.web> <system.web>
<webServices> <webServices>
<protocols> <protocols>
<remove name="HttpPost"/> <clear/>
<remove name="HttpGet"/> <add name="HttpSoap"/>
<add name="Documentation"/>
</protocols>
</protocols>
</webServices>
2008-4-21 </webServices>
</system.web>
</system.web>
Web Service Documentation
‡ The ASP.NET runtime uses reflection to generate two types of
documentation:
„ human-readable documentation (.asmx)
„ documentation used by client applications to interact with the
Web service (.asmx?WSDL)
‡ You can configure ASP.NET to display your custom
documentation when a user navigates to the .asmx file by
setting the wsdlHelpGenerator element within the
configuration file.
<system.web>
<webServices>
<wsdlHelpGenerator href="DefaultWsdlHelpGenerator.aspx" />
</webServices>
2008-4-21
</system.web>
SOAP Encoding Styles
‡ You can set the default encoding style value by decorating the class with
the SoapDocumentService or SoapRpcService attributes which belong to
System.Web.Services.Protocols Namespace.
‡ The SoapRpcService attribute supports only the RoutingStyle property.

Property Description

Specifies whether the parameters are wrapped in a single element within the
ParameterStyle
body of the SOAP message

Specifies whether the HTTP SOAPAction header should be populated or left


RoutingStyle
blank
Specifies whether the default for the encoding style of the messages is Literal or
Use
Encoded

[SoapDocumentService(SoapBindingUse.Literal,
SoapParameterStyle.Wrapped,
2008-4-21
RoutingStyle=SoapServiceRoutingStyle.SoapAction)]
SOAP Encoding Styles
‡ The SoapDocumentMethod and the SoapRpcMethod attributes are
associated with a particular Web method and can be used to override the
defaults set by their Web service counterparts
‡ The SoapRpcMethod attribute supports the same set of properties minus
the ParameterStyle and Use properties

2008-4-21
Interface Inheritance
‡ An interface defines a contract by which classes that inherit a particular
interface must support all the methods defined by the interface
‡ a Web service interface is defined within a WSDL document. A transport-
specific interface definition is represented by a binding definition, while a
transport-agnostic interface definition is represented by a portType
definition.
‡ How to:
„ Defines an abstract WebService and WebMethod
„ Let ASP.NET automatically generate the WSDL file
„ Remove its service definitions
„ Use the WebServiceBinding attribute to reference an interface defined within
another namespace
„ use the Binding property of the SoapDocumentMethod/SoapRpcMethod
attribute to reference the binding defined above
2008-4-21
Interface Inheritance
‡ Limitations:
„ you can reference only SOAP binding definitions
„ there is no validation either at compile time or at run time to ensure that the
Web service implements all the methods exposed by the inherited interface
‡ To ensure that the Web service supports all the methods of the inherited
interface, you can use the WSDL.exe tool to generate an abstract class
representing the interface. You can then add the resulting code to your
project and derive from the abstract class instead of the WebService class.

[ WebServiceBinding(Name="RemoteBinding",
Namespace="http://www.contoso.com/MyBinding",
Location="http://www.contoso.com/MySevice.asmx?wsdl")]
public class BindingSample : WebService {
[ SoapDocumentMethod(Binding=“RemoteBinding")]
[ WebMethod() ]
public string BindingMethod() {}
2008-4-21
}
Managing State - Session State
‡ ASP.NET uses a unique identifier that is passed by the client to
identify the session. This identifier can be saved in a cookie
maintained by the client or embedded within the URL of the
request. Even though Web Forms supports both, Web services
support only cookies.
‡ To enable the session state for a web service:
‡ Configure the sessionState element of the machine.config or
web.config configuration file and set the cookieless to false.
‡ Set the EnableSession property of the WebMethod attribute to true
on a per-Web-method basis.
‡ At the client side, set the proxy CookieContainer property.
‡ The Session Object can be got from the Session property of the
WebService Class.
2008-4-21
Managing State - Application State
‡ application state is always handled in process
‡ application state is not dependent on the client supporting cookies.
‡ Example: HitCounter

Initialize Application State in Global.asax file:


protected void Application_Start(Object sender, EventArgs e)
{ this.Application["HitCounter"] = (int)0; }
Locking Mechanism to Avoid Race Conditions:
try{
this.Application.Lock();
this.Application["HitCounter"] = (int)this.Application["HitCounter"]
+ 1; }
catch(Exception e) { // Handle exception ... }
2008-4-21
finally { this.Application.UnLock(); }
Raising Errors
‡ An error of type SoapException can be thrown when an error is
encountered within the Web services, which will be serialized into a
SOAP Fault message by the ASP.NET runtime.
‡ The faultstring, faultcode and detail element of Soap Fault can be
accessed by the Message, Code and Detail properties of the
SoapException Object.
‡ If an exception is thrown by the Web method that is not of type
SoapException, the ASP.NET runtime will serialize it into the body
of the SOAP Fault element. The faultcode element will be set to
Server.
Using System.Web.Services.Protocols;
XmlQualifiedName invalidSymbolsFaultCode =
new XmlQualifiedName("Client.InvalidSymbol","http://schemas.xmlso
ap.org/soap/envelope/");
2008-4-21

throw new SoapException("Invalid symbol.", invalidSymbolsFaultCode);


WSDL Tool

‡ WSDL.exe consumes the WSDL for a Web service


and then automatically generates proxy code
‡ WSDL.exe will map XML datatypes described
within the Web service's WSDL document to
their .NET equivalents
‡ the Add Web Reference Wizard is not as
configurable as WSDL.exe

2008-4-21
Command-Line Switches for
WSDL.exe

2008-4-21
Switch /appsettingurlkey example
To create the proxy:
wsdl /language:CS /namespace:BrokerageFirm
/appsettingurlkey:SecuritiesWebServiceUrl
http://woodgrovebank.com/Securities.asmx?wsdl

The Constructor in the proxy:


public Securities() {
string urlSetting =System.Configuration.ConfigurationSettings.App
Settings["SecuritiesWebServiceUrl"];
if ((urlSetting != null)) { this.Url = urlSetting;}
else {this.Url ="http://localhost/BrokerageFirm/Securities.asmx";
}
}
2008-4-21
Proxy Class
‡ The resulting proxy class generated by WSDL.exe is derived from the
SoapHttpClientProtocol class.
‡ For each operation, three methods are defined (just method signature, no
implementation code).
‡ Defines counterparts to the classes and enumeration types.
Selected Properties, Methods of the SoapHttpClientProtocol Class

2008-4-21
CookieContainer Property
‡ Proxies derived from SoapHttpClientProtocol fully support HTTP
cookies. However, the proxies have cookies disabled by default.
To enable cookie support to maintain session state, you must set
the CookieContainer property on the proxy object to reference an
instance of a CookieContainer object
‡ Once the proxy object has gone out of scope, all cookie
information will be invalid.

// Enable session state by creating a new cookie container.

securities.CookieContainer = new CookieContainer();

2008-4-21
Credentials Property
‡ The Credentials Property is used to hold the credentials when the
authentication mode is Windows.
‡ How to:
„ Set the mode attribute of <authentication> element in the web.config to
Windows
„ Set basic/Digest/Windows authentication for the web application in the IIS
administration tool
„ Get, Store and Transport your credentials with the credentials property of
the proxy class in the client side codes.

NetworkCredential creds=new NetworkCredential();


creds.UserName=UserName.Text; creds.Password=Password.Text;
CredentialCache cred_cache=new CredentialCache();
cred_cache.Add(new Uri(service.Url),"Basic",creds);
2008-4-21
Proxy.Credentials=cred_cache;
Stateless Web Service
Hi, I am savas
Banking
savas
Service
Welcome savas

I would like RMB1000 pls


Banking
savas
Service
No, can't do—don’t know you

2008-4-21
Stateful Grid Service
Hi, I am savas
Banking
savas
Service
Welcome savas

I would like RMB1000 pls


Banking
savas
Service
Your RMB1000

2008-4-21
Grid and Web Services to converge
‡ Web Services: applications on-demand
‡ Grid: computer-resources on-demand
‡ WS Resource Framework specification: defines
how to access stateful computer-resources (WS
resource) through a web service
‡ WSRF.NET: WSRF implementation on .NET
platform
http://www.cs.virginia.edu/~gsw2c/wsrf.net.html

2008-4-21

Вам также может понравиться