Web services allows you to connect to other applications, the data returned from web service is usually in xml or json format. In this tutorial, I'll show you how to create a web service in ASP.NET MVC using C#.
We will use Entity Framework Database First to practice our demo, if you don't already know about it. I think you should read Getting Started with Entity Framework Database First
Right click on your project->Add->New Item
Enter your web service name->Add
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebAppDemo
{
/// <summary>
/// Summary description for CustomerService
/// </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 CustomerService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public List<Customer> GetAll()
{
using (NorthwindEntities db = new NorthwindEntities())
{
return db.Customers.ToList();
}
}
}
}
Add the [WebMethod] attribute on the top of your method
To return the json format data, you can add the [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute at the top of your method.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Customer> GetAll()
{
using (NorthwindEntities db = new NorthwindEntities())
{
return db.Customers.ToList();
}
}
You can also add [SoapDocumentMethod(OneWay = true)] atribute to the method by which the return type is void to make your web service faster. Because the XML Web service client doesn't have to wait for the Web server to finish processing the XML Web service method.
[SoapDocumentMethod(OneWay = true)]
[WebMethod]
public void SendTicket(Ticket ticket)
{
}