Tuesday, 18 December 2012 17:54

how to write web service by c#

Written by 
Rate this item
(0 votes)

follow the steps to write web service in c# programming language-
opening a text editor,put the codes below and save the file as
web.asmx-
<%@ WebService Language="C#" class="WebService1" %>
using System;
using System.Web.Services;
[WebService(Namespace="http://www.yoursite.com/webservices/")]
class WebService {
[WebMethod]
public string SayingSomething() {
return "Hello all";}}

the first line in the above code,you show that it's a special
web service by the directive of WebService.

then you have to put any namespaces you need to use by using
keyword.you should include the System.Web.Services namespace.

the following line defines the namespace used to prevent
name crashes.
[WebService(Namespace="http://www.yoursite.com/webservices/")]
if it is not defined then http:/tempuri.org will be added as
default.whatever it is recommended to add the above line.

then expose methods as web method in the class by writing
[WebMethod] above any of your method.

test your web service in browsers like IE browser.suppose you
put your web service in the local server then you may want to
access it as follows-http://localhost/web.asmx.clicking
the link SayingSomething then invoke on next page,you get an
XML packet in return as the answer of the web service.

you should create a proxy class to consume your web service
by the following code in your command prompt-
wsdl "http://localhost/web.asmx" /out:web.cs

after that you will get a web.cs file generated by wsdl utility
in current directory.this wsdl utility come with the .NET
framework.to consume the file you have to compile it as dll by
the following command-
csc web.cs /t:library /out:web.dll /r:System.Web.Service.dll
/r:System.Xml.dll

put the file into the the directory /bin in your server.to
consume web service,use the following asp.net code -
<%@ Page Language="C#" %>
<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs e) {
WebService hs = new WebService();
TheLabel1.Text = hs.SayingSomething();
}
</script>
<html>
<head>
<title>hi WebService test</title>
</head>
<body>
<asp:Label id="TheLabel1" runat="server" />
</body>
</html>

Read 6929 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.