How To Write A Web Service In C#
An Overview
Allow's retrieve of a scenario where I am planning to testify information on regional, national and international news, weather data, ongoing sports scores and other personalized content in a web site. Just call back virtually how much effort and time it will take me to develop this application if I write the code for all these functionalities. On the other hand all these functionalities are already provided by other available sites. So, what if I can utilize this existing logic in my awarding? But, the question hither is "how I can use someone else's business logic in my application?".
For situations of this sort (& many other), we have techniques similar Web Services.
With Web Services, y'all can reuse someone else's business logic instead of replicating it yourself, using just a few lines of code. This technique is similar to what programmers currently do with libraries of APIs, DLLs or plug-ins. The main departure is that Web Services tin can be located remotely on another server.
When HTML pages (or the HTML output generated by ASP.NET spider web forms) are rendered in a browser for the end user, Web Services are invoked by other applications. They are pieces of business logic that are hosted somewhere on the internet and can be accessed by other applications.
Notation 1: Web Services are not limited to the .Cyberspace Framework. The standards were defined before .Cyberspace was released and they are exposed, used and supported by vendors other than Microsoft.
Annotation ii: Web Services are cantankerous-platform; a service written in one language tin be invoked by an application in some other language. The only requirement for accessing a service is an internet connection to make the HTTP asking.
Since a web service is cross-platform, there should be some usually understandable linguistic communication for requesting a service and getting a response from the service. Such a standard common language is XML. That'south why Spider web Services are built on XML-based standards for exchanging data.
As a result, the ready of information types Web Services can use is limited to the gear up of information types recognized by the XML Schema standard. So you tin use simple data types such equally strings and numbers to communicate with a spider web service and you tin can't send proprietary .Internet objects such every bit a FileStream, an Image or an EventLog. This restriction makes a lot of sense. Since other programming languages have no fashion to interpret these .Net objects, even if you lot could devise a style to ship them over the wire, the client might not be able to interpret them, that would thwart interoperability.
Annotation 3: If you need to work with .NET proprietary objects, you lot can go for .NET remoting. Information technology is a distributed engineering science that allows apply of .Net objects. But non-.Net clients can't consume it.
Hither's the list of supported data types
- Congenital-in types (The Nuts): The built in C# data types such as short, int, long, ushort, uint, ulong, float, double, decimal, bool, string, char, byte and DateTime.
- Objects: You can utilize an object of any user defined class. If your class has methods, these methods will not be transmitted to the client.
- Arrays: Arrays of any supported blazon (congenital-in or custom objects). Yous tin besides use an ArrayList (that is but converted into an array).
- Enumerations: Enums are supported. Nonetheless, a web service uses the string name of the enumeration value, not the underlying integer.
- XmlNode: Objects based on System.Xml.XmlNode represent a portion of an XML document. You can apply this to send capricious XML.
- DataSet and DataTable : DataSet and DataTable are immune. Merely other ADO.Net information objects, such equally DataColumns and DataRows, aren't supported.
Create a web service
A web service is a unproblematic asmx page.
Here I will utilize Visual Studio 2012 (though you tin use any editor), with the .Cyberspace Framework 3.five to create a web service.
Up to framework three.5, Visual Studio provides a directly template for Spider web Services. Starting from 4, it doesn't provide whatsoever direct template, so you need to create a web application and add a spider web service to your awarding (correct-click on your web application → Add → New Item → WebService).
Allow's create a unproblematic service that will return a sum of 2 integers.
Open Visual Studio in Ambassador style. File → New → Projection so select .Net Framework iii.5 (on the top) then select ASP.NET web service application then name your project (I named information technology MyWebServiceDemo) then click OK.
Visual Studio will create a spider web service boilerplate (Service1.asmx and Service1.asmx.cs) for you. Now, let's clarify this template created by Visual Studio.
Note the following In Service1.asmx.cs:
- An additional namespace "System.Spider web.Services" is included along with the 4 default namespaces that Visual Studio includes for spider web application.
- The "Service1" class is inherited from "Organization.Spider web.Services.WebService". Past inheriting a grade from "Organisation.Web.Services.WebService", you tin can access born ASP.Net objects such equally (Awarding, Session, User, Context, server). If you lot don't need congenital-in objects of .Net, you lot don't demand to inherit your service class from "WebService".
- "Service1" is decorated with a "WebService(Namespace = "http://tempuri.org/" )" aspect. If you want to expose a grade as a service, yous need to decorate it with the "WebService" attribute. This WebService aspect has several backdrop like:
- Namespace: This belongings makes a service uniquely identifiable. This is an XML property. A client application may be consuming several services, and so at that place is the probability of a naming standoff. To avoid this, information technology's service providers responsibility to utilize a unique namespace.
- Proper name: Apply this property to provide a descriptive proper noun to your service.
- Clarification: To provide a brief description on the service.
- "Service1" has another attribute "WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)". This is to bespeak the standard which service is following. If the service does not confirm to this standard, you volition become an exception.
- One more aspect service is decorated with is "[Arrangement.Web.Script.Services.ScriptService]", to make a service accessible from the customer script, it should exist decorated with this attribute.
- The Service1 class has a method HelloWorld that is decorated with a "[WebMethod]" aspect. The methods of the service that are to be accessed by the client awarding should be decorated with this attribute. At that place may be some method that the service is using for some internal functionality, client applications don't need to admission them. Don't decorate such methods with a WebMethod attribute. The WebMethod attribute besides has Proper noun and Description properties that you can utilize to provide a self describing proper noun or description respectively.
Now let'south see the marking up. Right-click on Service1.asmx in Solution Explorer and then select view mark up. In Service1.asmx, you volition see that there is only a WebService directive with some attributes, since a service will be invoked by some awarding not by whatever end user. So the asmx page has no mark up.
<%@ WebService Language="C#" CodeBehind="Service1.asmx.cs" Class="MyWebServiceDemo.Service1"%>
- The "WebService" directive, indicates this asmx page is a web service.
- The "Language="C#"", is to indicate language used for this service.
- The "CodeBehind" property is nothing to do with ASP.NET or web service, this is completely a Visual Studio holding, that is used to map the asmx page with information technology'south code backside folio.
- The "Class" property holds fully qualified name of service course. This marks the entry point of service like chief() in C programming language.
Now, run your application by hitting F5, http://localhost:56655/Service1.asmx volition open in your browser (the port number may vary). Y'all volition find a link for Service Description, that will redirect to the WSDL document of the service, some other link for HelloWorld (list for methods exposed past service) that will redirect to a page for testing this method.
Implementing a web service
Now let's implement the service. Rename the "Service1" file in Solution Explorer to something convenient like "MyService". Modify the class proper name from Service1 to MyService. Open up the mark upwards (asmx) page.
Equally yous tin can run across hither Visual Studio is unable to resolve "Service1" in the class property, since the course indicates a fully qualified name of the service and we renamed our Service1 course to MyService. So Visual Studio is unable to resolve it. So, now change the form property to "MyWebServiceDemo.MyService". Modify the "CodeBehind" holding from "Service1.asmx.cs" to "MyService.asmx.cs" as we renamed the file also.
MyService.asmx
<%@ WebService Language="C#" CodeBehind="MyService.asmx.cs" Class="MyWebServiceDemo.MyService"%>
MyService.asmx.cs
using System.Web.Script.Serialization; using System.Spider web.Services; namespace MyWebServiceDemo { // Utilise "Namespace" attribute with an unique proper noun,to brand service uniquely discoverable [WebService(Namespace = "http://tempuri.org/")] // To point service confirms to "WsiProfiles.BasicProfile1_1" standard, // if not, information technology volition throw compile time error. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To restrict this service from getting added every bit a custom tool to toolbox [Organisation.ComponentModel.ToolboxItem(fake)] // To allow this Web Service to be called from script, using ASP.Internet AJAX [System.Web.Script.Services.ScriptService] public grade MyService : WebService { [WebMethod] public int SumOfNums(int Outset, int 2nd) { render First + Second; } } }
At present, the service is ready to be used, let's compile and test it.
Exam a web service
Let's run the project by hitting F5. The "http://localhost:56655/MyService.asmx" page will open that has a link for the Service clarification (the WSDL document, documentation for web service) another link for SumOfNums, which is for test page of SumOfNums method.
Let's employ method overloading of the OOP concept. Add the following WebMethod in MyService class.
[WebMethod] public bladder SumOfNums(float Offset, float 2d) { return First + Second; }
Hit F5 to run the application, yous volition get "Both Single SumOfNums(Single, Single) and Int32 SumOfNums(Int32, Int32) employ the message proper noun 'SumOfNums'. Use the MessageName belongings of the WebMethod custom aspect to specify unique message names for the methods." error message. We only used method overloading concept, then why this error message? This is because these methods are non unique for a customer application. Every bit the error message suggests allow's apply the MessageName belongings of the WebMethod attribute as shown below:
[WebMethod (MessageName = "SumOfFloats")] public float SumOfNums(float Outset, bladder Second) { return Offset + Second; }
Now, compile and run the application. Once more it's showing some dissimilar error bulletin "Service 'MyWebServiceDemo.MyService' does not conform to WS-I Basic Profile v1.1". As, WsiProfiles.BasicProfile1_1 doesn't support method overloading we are getting this exception. At present, either remove this "[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]" attribute or make it "[WebServiceBinding(ConformsTo = WsiProfiles.None)]".
using System.Web.Script.Serialization; using System.Web.Services; namespace MyWebServiceDemo { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.None)] [System.ComponentModel.ToolboxItem(false)] [System.Spider web.Script.Services.ScriptService] public course MyService : WebService { [WebMethod] public int SumOfNums(int Starting time, int 2nd) { render Starting time + Second; } [WebMethod(MessageName = "SumOfFloats")] public float SumOfNums(bladder First, bladder Second) { return First + Second; } } }
Now y'all tin can employ method overloading in the service.
The Test page
Click on SumOfNums, y'all will be redirected to "http://localhost:56655/MyService.asmx?op=SumOfNums". You will come across here that just "?op=SumOfNums" is appended to the service URL. This page has 2 text boxes for 2 input values (Starting time, Second) that the SumOfNums method takes as an input parameter and a button "Invoke", clicking on which you'll exist redirected to: "http://localhost/WebServiceForBlog/MyService.asmx/SumOfNums" that is has the value that the SumOfNums method returned in XML format. Similarly, by clicking on "SumOfNums MessageName="SumOfFloats"", you lot will exist redirected to "http://localhost:56655/MyService.asmx?op=SumOfFloats". So the "SumOfNums MessageName="SumOfFloats"" method will be known as "SumOfFloats" for client applications.
Now, the question is, from where does this test page come? We never added whatsoever marker up only still a page was rendered!
The examination pages aren't part of the Web Services; they're just a frill provided by ASP.NET. The test page is rendered past ASP.Cyberspace using the web page c:\[WinDir]\Microsoft. NET\Framework\[Version] \Config\DefaultWsdlHelpGenerator.aspx. "Reflection" concept to render the examination folio.
You can besides modify this test folio for which you just need to re-create the DefaultWsdlHelpGenerator.aspx file to your spider web application directory, modify information technology and give it a name. I named it "MyWsdlHelpGenerator.aspx" and then changed the web.config file for the application past adding the <wsdlHelpGenerator> element, as shown here:
<configuration> <system.spider web> <webServices> <wsdlHelpGenerator href="MyWsdlHelpGenerator.aspx"/> </webServices> </arrangement.web> </configuration>
The WSDL document
Web Services are cocky-describing, that means ASP.NET automatically provides all the information the customer needs to eat a service as a WSDL certificate. The WSDL document tells a customer what methods are present in a web service, what parameters and render values each method uses and how to communicate with them. WSDL is a XML standard. We'll explore the WSDL document in our next articles.
Host a spider web service
Since we will add a reference to this service and consume information technology from various applications and the port number is supposed to change, permit's host this service on IIS to take a specific address of a service. Open up IIS, go to the default spider web sites node then seelct Add together Application and then provide an alias name (I gave it WebServiceForBlog) then browse to the physical location of your service for the physical path field so click "OK". You can now browse with an allonym name (similar http://localhost/WebServiceForBlog/) to test if the application was hosted properly. You'll get a "HTTP Error 403.14 – Forbidden" error since there is no default document set for this application. Add a "MyService.asmx" page as a default certificate. Now yous tin scan your service.
How to access a web service from a customer application
Here our main focus will exist on consuming a web service. Let'southward quickly create a spider web service (or alter, if y'all have already created i).
MyService.asmx
<%@ WebService Linguistic communication="C#" CodeBehind="MyService.asmx.cs" Course="MyWebServiceDemo.MyService" %>
MyService.asmx.cs
using System.Spider web.Script.Serialization; using System.Web.Services; namespace MyWebServiceDemo { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.None)] [System.ComponentModel.ToolboxItem(false)] [Organisation.Web.Script.Services.ScriptService] public course MyService { // Takes 2 int values & returns their summation [WebMethod] public int SumOfNums(int First, int Second) { return Commencement + Second; } // Takes a stringified JSON object & returns an object of SumClass [WebMethod(MessageName = "GetSumThroughObject")] public SumClass SumOfNums(string JsonStr) { var ObjSerializer = new JavaScriptSerializer(); var ObjSumClass = ObjSerializer.Deserialize<SumClass>(JsonStr); render new SumClass().GetSumClass(ObjSumClass.Offset, ObjSumClass.2d); } } // Normal class, an instance of which will be returned by service public class SumClass { public int First, 2d, Sum; public SumClass GetSumClass(int Num1, int Num2) { var ObjSum = new SumClass { Sum = Num1 + Num2, }; return ObjSum; } } }
Compile this awarding. Since we will swallow this service from other applications we need a fixed accost for this service, the port numbers are supposed to vary. So, host the web service on IIS (refer to the previous commodity for hosting the spider web service). I hosted it with the virtual directory "WebServiceForBlog".
How to consume a web service
Let's add another projection to our solution. Y'all tin also create a new project. I am adding to the same solution, so that it volition not need me to open several instances of Visual Studio. When developing and testing a web service in Visual Studio, information technology's ofttimes preferred to add both the web service and the client application to the aforementioned solution. This allows you to examination and modify both pieces at the same time. You tin even use the integrated debugger to set breakpoints and step through the code in both the client and the server.
Right-click on solution, select Add together → New project then seelct ASP.NET Empty Application then name your application, I am naming it "ServiceConsumer".
Add a Web Form, I proper noun it "Home.aspx".
On the click of a push in this folio, nosotros will call our service.
For calling a Spider web Service you need a proxy object that volition handle the complexities of sending a Lather asking and response messages.
To create this proxy class, you need a reference to the service class. Correct-click on this project so select Add together service reference, a window volition open, type the URL of your service, click on notice, you will see all the webmethods exposed by your service listed. At the bottom of the window, there'll be a field for Namespace. Provide a name for the namespace in which the proxy class of the referenced service will be generated, I am giving it "MyServiceReference". Now, click on "Go".
Past adding a service reference, we created a proxy class of the referenced service to the current projection (client app).
The proxy class wraps the calls to the web service's methods. It takes care of generating the right SOAP message format and managing the transmission of the messages over the network using HTTP and converting the results received dorsum to the respective .NET data types.
Now, add mark upward in Home.aspx to receive inputs. Here's my mark up.
<table> <tr> <td>First Number:</td> <td><input type="text" id="Text1" runat="server" /></td> </tr> <tr> <td>Second Number:</td> <td><input type="text" id="Text2" runat="server" /></td> </tr> <tr> <td><input blazon="button" onserverclick="AddNumber" value="Add" runat="server" /></td> <td><div id="divSum" runat="server"></div> <div id="divSumThroughJson" runat="server"></div></td> </tr> </tabular array>
Dwelling house.aspx.cs
using System; using ServiceConsumer.MyServiceReference; namespace ServiceConsumer { public partial class Home : System.Spider web.UI.Page { protected void Page_Load(object sender, EventArgs east) {} protected void AddNumber(object Sender, EventArgs E) { int Num1, Num2; int.TryParse(txtFirstNum.Value, out Num1); int.TryParse(txtSecondNum.Value, out Num2); // creating object of MyService proxy class var ObjMyService = new MyServiceSoapClient(); // Invoke service method through service proxy divSum.InnerHtml = ObjMyService.SumOfNums(Num1, Num2).ToString(); var ObjSumClass = new SumClass { First = Num1, Second = Num2 }; var ObjSerializer = new JavaScriptSerializer(); var JsonStr = ObjSerializer.Serialize(ObjSumClass); divSumThroughJson.InnerHtml =ObjMyServiceProxy.GetSumThroughObject(JsonStr).Sum.ToString(); } } }
How to eat a web service from a client script
Add together another project to your solution. I named it "ConsumeServiceFromClientScript". Add a web form (permit's say Default.aspx).
Creating a JavaScript proxy
JavaScript proxies can be automatically generated past using the ASP.NET AJAX ScriptManager control's Services holding. You tin define one or more than services that a page tin telephone call asynchronously to transport or receive data using the ASP.NET AJAX "ServiceReference" control and assigning the Web Service URL to the control's "Path" property.
Add a ScriptManager control like the post-obit inside the course tag:
<asp:ScriptManager runat="server"> <Services> <asp:ServiceReference Path="http://localhost/WebServiceForBlog/MyService.asmx"/> </Services> </asp:ScriptManager>
When you add together a reference to a spider web service (MyService.asmx) from a page using a ScriptManager command, a JavaScript proxy is generated dynamically and referenced past the folio. Now if yous the cheque folio source in a browser, you can notice that:
http://localhost/MyWebServiceDemoService/MyService.asmx/js
Or:
http://localhost/MyWebServiceDemoService/MyService.asmx/jsdebug
Is included in your page with a script tag depending on whether debugging is enabled In your projection.
Add an empty Web form to your project. I named it "Default.aspx".
Default.aspx
<body> <form id="form1" runat="server"> <asp:ScriptManager runat="server"> <Services> <asp:ServiceReference Path="http://localhost/WebServiceForBlog/MyService.asmx"/> </Services> </asp:ScriptManager> <div> <table> <tr> <td>First Number:</td> <td><input type="text" id="txtFirstNum" /></td> </tr> <tr> <td>Second Number:</td> <td><input type="text" id="txtSecondNum" /></td> </tr> <tr> <td><input blazon="button" onclick="AddNumber();" value="Add together" /></td> <td><div id="divSum1"></div><div id="divSum2"></div><div id="divSum3"></div><div id="divSum4"></div><div id="divSum5"></div></td> </tr> </table> </div> </form> <script blazon="text/javascript" src="Scripts/jquery-1.7.1.js"></script> <script type="text/javascript" src="Scripts/json2.js"></script> <script type="text/javascript"> function AddNumber() { var FirstNum = $('#txtFirstNum').val(); var SecondNum = $('#txtSecondNum').val(); $.ajax({ type: "POST", url: "http://localhost/WebServiceForBlog/MyService.asmx/SumOfNums", information: "Start=" + FirstNum + "&Second=" + SecondNum, // the data in form-encoded format, information technology would appear on a querystring //contentType: "awarding/x-www-form-urlencoded; //charset=UTF-8" //class encoding is the default one dataType: "text", crossDomain: true, success: function (information) { $('#divSum1').html(information); } }); // i/p in JSON format, response as JSON object $.ajax({ type: "POST", url: "http://localhost/WebServiceForBlog/MyService.asmx/SumOfNums", data: "{Commencement:" + FirstNum + ",Second:" + SecondNum + "}", contentType:"awarding/json; charset=utf-viii",// What I am ing dataType: "json", // What I am expecting crossDomain: true, success: part (information) { $('#divSum2').html(data.d); } }); // i/p as JSON object, response as plain text $.ajax({ type: "POST", url: "http://localhost/WebServiceForBlog/MyService.asmx/SumOfNums", data: { Starting time: FirstNum, Second: SecondNum }, contentType: "awarding/x-www-form-urlencoded; charset=UTF-8", crossDomain: true, dataType: "text", success: function (data) { $("#divSum3").html(data); } }); // Url encoded stringified JSON object equally I/p & text response var ObjSum = new Object(); ObjSum.Offset = FirstNum; ObjSum.2nd = SecondNum; $.ajax({ type: "Post", url: "http://localhost/WebServiceForBlog/MyService.asmx/GetSumThroughObject", data: "JsonStr=" + JSON.stringify(ObjSum), dataType: "text", crossDomain: truthful, success: role (data) { $('#divSum4').html($(data).find('Sum').text()); } }); // Call SOAP-XML spider web services directly var SoapMessage = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-example" xmlns:xsd="http://world wide web.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/lather/envelope/"> \ <lather:Body> \ <SumOfNums xmlns="http://tempuri.org/"> \ <Showtime>'+FirstNum+'</First> \ <2nd>'+SecondNum+'</Second> \ </SumOfNums> \ </soap:Body> \ </soap:Envelope>'; $.ajax({ url: "http://localhost/WebServiceForBlog/MyService.asmx?op=SumOfNums", type: "Post", dataType: "xml", information: SoapMessage, consummate: ShowResult, contentType: "text/xml; charset=utf-8" }); } function ShowResult(xmlHttpRequest, status) { var SoapResponse = $(xmlHttpRequest.responseXML).notice('SumOfNumsResult').text(); $('#divSum5').html(SoapResponse); } </script> </body>
Notation: For demo purposes, I have difficult-coded the service URL. Simply it'south non a practiced practice. Y'all can proceed the service URL in the spider web.config and use RegisterClientScriptBlock or RegisterStartUpScript depending on your requirements to use this service URL in client script.
Call SOAP-XML Web Services directly
In society to call the web service, we need to supply an XML message that matches the functioning definition specified by the web service's WSDL. In the test page "http://localhost/WebServiceForBlog/MyService.asmx?op=SumOfNums" you can see a sample of Lather 1.1/1.2 request and response format. From which you can become the operations schema. Now, you simply need to exchange the blazon names for the operation's parameters, with their actual values. Re-create the Lather envelope to the Default.aspx page and supersede the place holders (type names) with an bodily value.
A sample for this blazon of telephone call is included in the lawmaking snippet above. The variable "SoapMessage" in the preceding instance contains the consummate XML message that we're going to transport to the web service. On completion of the ajax asking, nosotros volition call a call back method named "ShowResult".
Note:.NET 1.x supports SOAP 1.1 simply. From .NET 2.0 Both SOAP1.i and SOAP1.2 are supported unless one is restricted explicitly. If you want to change this, you can disable either one through the web.config file:
<configuration> <system.web> <webServices> <protocols> <!-- To disable SOAP 1.2 --> <remove proper noun="HttpSoap12"/> <!-- To disable Soap 1.1 --> <remove name="HttpSoap"/> </protocols> </webServices> </organisation.web> </configuration>
References
Book: Programming .NET Web Services By Alex Ferrara, Matthew MacDonald
Book: Pro ASP.NET three.v in C# by Matthew MacDonald , Mario Szpuszta
Agreement ASP.NET AJAX Web Services
How To Write A Web Service In C#,
Source: https://www.c-sharpcorner.com/UploadFile/00a8b7/web-service/
Posted by: rileylecrid.blogspot.com
0 Response to "How To Write A Web Service In C#"
Post a Comment