Reputation: 6873
I am constantly finding a good guide about how to write a web service using .NET with Visual Studio 2010 so I can utilize it with my HTML based website using AJAX.
I know there was a way called the ASMX way but now it's more updated to ServiceHost so what I need is a simple guide which can drive me through how to create asp.net web service using ServiceHost object.
Sorry if it sounds ambiguous or childish.
Upvotes: 1
Views: 702
Reputation: 5128
Place the ScriptManager control on your page and add a reference to your .asmx
service:
<asp:ScriptManager ID="myManager" runat="server">
<Services>
<asp:ServiceReference Path="~/MyService.asmx" />
</Services>
</asp:ScriptManager>
In the code-behind of your web-service declare you web method (notice the ScriptService attribute):
namespace MyServices
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string SayHello(name)
{
return "Hello, " + name;
}
}
}
Now you can consume the web-service from the Javascript like the following:
function queryWebService() {
MyServices.MyService.SayHello('Bobby',
function(result, userContext) {
alert('Web-service response: ' + result);
}, function(result) {
alert('Error!');
});
}
UPDATE
If you want to consume the web-service by simply sending an HTTP GET requests then you can do the following:
Decorate your web-method with a ScriptMethod attribute:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string SayHello(name)
{
return "Hello, " + name;
}
Notice the UseHttpGet property which is set to True
. You probably also need to modify the web.config
file to allow this kind of interaction:
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
Now you can make a simple HTTP GET request to your web-service like shown below (the example uses jQuery.ajax):
$.ajax({
url: "/MyService.asmx/SayHello?name=Bobby",
success: function(transport) {
alert('Web-service response: ' + transport.responseText);
}
});
Hope this will help you.
Upvotes: 2