How to consume WCF service in MVC

Here we going to discuss about how to  consuming the WCF service in MVC. For creating WCF refer here

Step 1:

Create a new project and add Service References by right click the project as show below

Consume-WCF 1

and in Add Service Reference wizard, enter the address of the service and click ok button to check the availability of the service method. we can also change the namespace to consumed service. Finally click ok to add the service reference to our application

Consume-WCF 2

Step 2:

Check whether service added correctly as like below screen by double click the service name to open the object browser window (check with web config file for reference)

Consume-WCF 4

If service name space is not added correctly in the above screen then right click the the service and choose Configure Service Reference’, in that wizard unchecked the Reuse types in referenced assemblies’ options and click ok ( it will update in webconfig also )

Consume-WCF 3

Step 3:

Create Controller to implement the service.

public ActionResult Index()
{
ServiceReference1.Service1Client uDetail = new ServiceReference1.Service1Client();
string uName = uDetail.DisplayUserName(“Aadharsh GK”);
return Content(uName);
}

Here i am creating instance for the service and passing the parameter to get result string.

Step 4:

Run the application

Output
Consume-WCF 6

Advertisements