Ví dụ thực hành cơ bản về SOAP, WSDL và ASP.NET

Ví dụ thực hành cơ bản về SOAP, WSDL và ASP.NET

Web Serivce là một công nghệ cho phép client truy xuất để thực hiện mọi tác vụ như một Web Application. Về bản chất, Web service dựa trên XML và HTTP, trong đó XML làm nhiệm vụ mã hóa và giải mã dữ liệu và dùng SOAP để truyền tải. Web Service không phụ thuộc vào platform nào, do đó bạn có thể dùng Web Service để truyền tải dữ liệu giữa các ứng dụng hay giữa các platform.

>> Giới thiệu 7 khái niệm quan trọng về Web Service

>> Xây dựng ứng dụng áp dụng RESTful Web Services – xử lý object

>> Giới thiệu về RESTful Web Services

Sơ đồ tương tác giữa User và Web Service:

UservsWebService.JPG

SOAP – Simple Object Access Protocol

SOAP – Một tiêu chuẩn của W3C, là giao thức sử dụng XML để định nghĩa dữ liệu dạng thuần văn bản (plain text) thông qua HTTP. SOAP là cách mà Web Service sử dụng để truyền tải dữ liệu. Vì dựa trên XML nên SOAP là một giao thức không phụ thuộc platform cũng như bất kì ngôn ngữ lập trình nào.

Một thông điệp SOAP được chia thành hai phần là header và body. Phần header chỉ ra địa chỉ Web Service, host, Content-Type, Content-Length tương tự như một thông điệp HTTP.
Khi tạo một dự án Web Service, mặc định Web Visual Develop sẽ tạo cho bạn phương thức HelloWorld() sau:

public string HelloWorld()
{
return "Hello World";
}

Một HTTP Request sẽ có dạng sau:

POST /MathService.asmx/HelloWorld HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length

Đối với SOAP (v1.2)

Request:

POST /MathService.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<HelloWorld xmlns="http://tempuri.org/" />
</soap12:Body>
</soap12:Envelope>

Trong phầncủa đoạn SOAP request trên, thẻđược dùng để các phần tử con tương ứng với các dữ liệu mà phương thức HelloWorld yêu cầu để làm tham số. Bởi vì phương thức HelloWorld không yêu cầu bất kì tham số nào, nên thẻ này cũng không có bất kì phần tử con nào.

Response:

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<HelloWorldResponse xmlns="http://tempuri.org/">
<HelloWorldResult>string</HelloWorldResult>
</HelloWorldResponse>
</soap12:Body>
</soap12:Envelope>

Phương thức HelloWorld() của WebService trả về dữ liệu có dạng string, và bạn có thể thấy rõ điều này trong thẻ <soap12:Body>. Nếu cần tìm hiểu thêm về SOAP, bạn có thể tham khảo các bài hướng dẫn trên W3schools: http://www.w3schools.com/soap/default.asp

WSDL – Web Services Description Language

WSDL là ngôn ngữ được sử dụng để mô tả đầy đủ về Web Service theo chuẩn XML như các phương thức, kiểu dữ liệu,… dựa trên XML schema. Ví dụ một đoạn định nghĩa kiểu dữ liệu của WSDL cho phương thức HelloWorld() trên:

[…] <wsdl:types> <s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/"> <s:element name="HelloWorld"> <s:complexType /> </s:element> <s:element name="HelloWorldResponse"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="HelloWorldResult" type="s:string" /> </s:sequence> </s:complexType> </s:element> </s:schema> </wsdl:types> […]

Trong đó, phần định nghĩa các kiểu dữ liệu dùng cho request được đặt tên dựa theo tên phương thức “HelloWorld”:

<s:element name="HelloWorld">
<s:complexType />
</s:element>

Theo sau đó là phần định nghĩa các kiểu dữ liệu dùng để response được đặt tên “HelloWorldResponse”:

<s:element name="HelloWorldResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="HelloWorldResult" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>

Việc đặt tên này cần thiết để sử dụng trong phần định nghĩa message phía sau. Tham khảo hướng dẫn về XML Schema và WSDL tại các link sau:

http://www.w3schools.com/wsdl/default.asp

http://www.w3schools.com/schema/

Tạo một ASP.NET Web Service đơn giản

Trong .Net, bạn tạo ra một Web Service ra bằng cách tạo một subclass của lớp System.Web.Services.WebService, sau đó định nghĩa các phương thức có thể được triệu gọi từ client. Các phương thức này phải được đánh dấu với attribute [WebMethod].
Khi tạo một dự án mới, nếu bạn đặt phiên bản .Net sử dụng là 4, template Web Service sẽ không tồn tại do Microsoft nghĩ rằng template đó quá đơn giản. Vì vậy muốn tạo một project Web Service, bạn phải chuyển phiên bản .Net sang 3.5 . Ở đây tôi vẫn sử dụng phiên bản .Net 4 và tạo một project ASP.NET Empty Web Application với tên là Y2FirstWebService.

 Web Service

Tiếp đó bạn thêm item Web Service (phím tắt Ctrl + Shift + A để mở cửa sổ Add New Item) với tên là HelloService.asmx.

[IMG]

File code-behind HelloService.asmx.cs khi được tạo ra đã chứa sẵn phương thức HelloWorld().

HelloService.asmx:
<%@ WebService Language=”C#” CodeBehind=”HelloService.asmx.cs” %>
HelloService.asmx.cs (v1):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Y2FirstWebService
{
/// <summary>
/// Summary description for MathService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class HelloService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}

Bạn có thể nhấn F5 chạy thử, trình duyệt sẽ mở ra và hiển thị đường link với nội dung HelloWorld. Đây chính là tên của phương thức của lớp HelloService trên. Nhấn vào link này, bạn được đưa đến một trang dùng để test phương thức HelloWorld.

[IMG]

Note: Bạn có thể xem nội dung WSDL được tạo ra để mô tả cho Web Service này bằng cách bằng cách nhấn vào link Service Description với địa chỉ có dạng (chạy trên localhost, port của bạn có thể khác):  http://localhost:1107/MathService.asmx?WSDL.

Bên dưới bạn có thể thấy thông điệp SOAP request và response sẽ được sử dụng để giao tiếp giữa client với Web Service. Nhấn nút Invoke, trình duyệt sẽ mở ra một trang mới với nội dung theo định dạng XML, kết quả thực sự trả về của phương thức là nội dung nằm trong thẻ <string>:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<string xmlns=”http://tempuri.org/“>Hello World</string>
Bây giờ ta thêm một phương thức mới với tên Hello, đồng thời tạo thêm class Person để làm kiểu trả về cho phương thức Hello() này.
HelloService.asmx.cs (v2):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Y2FirstWebService
{
/// <summary>
/// Summary description for MathService
/// </summary>
// [WebService(Namespace = "http://tempuri.org/")]
// [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// [System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class HelloService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}

[WebMethod]
public Person Hello(string name, int age)
{
return new Person { Name = name, Age = age };
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}

Chạy lại Web Service và kiểm tra phương thức Hello(), giao diện trang web sẽ thay đổi cho phép bạn nhập tham số vào:

[IMG]

Nhập tên vào textbox và nhấn Invoke, trình duyệt sẽ mở ra trang kết quả:

<?xml version="1.0" encoding="utf-8" ?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Name>Yin Yang</Name>
<Age>10</Age>
</Person>

Phần kết

Vậy là bạn đã tạo được một Web Service, và như bạn có thể thấy, công việc thật đơn giản.

Bạn thấy bài viết này như thế nào?: 
Average: 7.6 (25 votes)
Ảnh của Khanh Hoang

Khanh Hoang - Kenn

Kenn is a user experience designer and front end developer who enjoys creating beautiful and usable web and mobile experiences.

Bình luận (0)

 

Add Comment

Filtered HTML

  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Các thẻ HTML được chấp nhận: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Tự động ngắt dòng và đoạn văn.

Plain text

  • No HTML tags allowed.
  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Tự động ngắt dòng và đoạn văn.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Máy tính bảng 7 inch “rủ nhau” giảm giá

Máy tính bảng 7 inch “rủ nhau” giảm giá

Một loạt máy tính bảng 7 inch trên thị trường đã được giảm giá. Cụ thể là, Galaxy Tab P7000 giảm gần 2 triệu đồng trong khi HTC Flyer cũng chỉ còn bán với giá 11,5 triệu...

Safari dẫn đầu thị phần Browser mobile trong tháng 3/2013

Safari dẫn đầu thị phần Browser mobile trong tháng 3/2013

Theo thống kê mới nhất của Net Applications, trong tháng 3 trình duyệt Safari của Apple đã dẫn đầu với 61,79% thị phần, tăng mạnh 6,38% so với tháng 2.

Mozilla Firefox 8 chính thức phát hành

Mozilla Firefox 8 chính thức phát hành

Mozilla đã tung ra phiên bản ổn định của trình duyệt Firefox 8 vào hôm qua, ngày 8/11. Nhiều tính năng mới đã được thêm vào như tích hợp tìm kiếm trong Twitter...

Công ty diệt chuột T&C

 

Diet con trung