Integration Of WCF And MVC

In this article you will learn about the Integration of WCF and MVC.

Introduction

While working with Android department for one of my project I came through a problem of writing HTML tags in one string to format email properly. Then an idea came up in my mind to format using views that I am using for that project website and started thinking of integration of WCF and MVC.

Both projects are 100 % complete, just one thing I was confident about was using cshtml I can format my mail for WCF. For other things I need to work more and research. After lot of time, searching got a solution that was pleasing.

Background

To Learn this topic , you should be familiar with WCF and MVC basics.

Using the code

Let us start!

Firstly, create WCF Service Application. You will see some basic service and interface creation. Now Service Application is ready, now we need MVC Environment. For that we will add MVC to project using Nuget Package Tool.

nuget

Install-Package Microsoft.AspNet.Mvc -Version 5.2.3

Package 

Now MVC and WCF is merged but still to work with MVC  these three things are prerequisite: Model ,View and Controller.

Let us start with View.

Create folder at root level named "Views". As in this article I am working with Partial View, so as a good practice I am creating "Shared" folder inside that. To add Partial View right click on "Views" folder, select View, name it and check Partial view check box as in the following screenshot,

add view

For MVC project 2 web.config files are used one at root level and one inside Views folder.

So now next step is to add web.config file to Views folder. (Copy web.config file from any mvcProject, you can also copy it from mine demo Project, While copying don't forgot to update namespace of your project inside web.config file).

xml

MVC is working with Routing concept and for that it use Route.config file, so MVC structure will add first.

"App_Start" folder at root level. After that add Route.configfile (copy it from any .NET MVcProject and update its namespace as well.)

As we are merging WCF with MVC, Routing must allow svc files. For that we need to ignore route for file with ".svc" extension.

routeconfig

We have added route.config file, but while starting the application we need to register this root. For that we will add Global.asax file to our project by right click and add new file.

In global.asax file there is a function named "Application_Start" where we will add line to register route. First you need to add one namespace "System.Web.Routing;" for RouteTable.

RouteConfig.RegisterRoutes(RouteTable.Routes);

Everything is done to format email, I have taken Partial view but Model is remaining. For that I will add two class files OrderDetail.cs and OrderItem.cs to display order related data.

My Main Motto for this idea was to send mail with formatting without writing tags as a string.

So now I need to add method to format PartialView to String. For that I have added the following Static method,
  1. public static string RenderViewToString(string controllerName, string viewName, object viewData)   
  2. {  
  3.     using(var writer = new StringWriter())   
  4.     {  
  5.         varrouteData = new RouteData();  
  6.         routeData.Values.Add("controller", controllerName);  
  7.         varfakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null"http://google.com"null), new HttpResponse(null))), routeData, new FakeController());  
  8.         varrazorViewEngine = new RazorViewEngine();  
  9.         varrazorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, ""false);  
  10.   
  11.         varviewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);  
  12.         razorViewResult.View.Render(viewContext, writer);  
  13.         returnwriter.ToString();  
  14.     }  
  15. }  
For MVC Controller is the main part, so for working with this method we need to add one controller. Let us name it FakeController.

public class FakeController : ControllerBase { protected override void ExecuteCore() { } }


Now everything is ready for Email.

Let us code for Service method to send an email where I will use View to string conversion method.
  1. stringOrderDetail = Utility.RenderViewToString("Temp""~/Views/Shared/_OrderInvoice.cshtml", Order);  
  2.   
  3. public string GetData()   
  4. {  
  5.     OrderDetail Order = new OrderDetail();  
  6.     Order.OrderId = Guid.NewGuid();  
  7.     Order.OrderedOn = DateTime.Now;  
  8.     OrderItemorderItem = null;  
  9.     Order.items = new List < OrderItem > ();  
  10.     for (inti = 0; i < 5; i++)  
  11.     {  
  12.         orderItem = new OrderItem();  
  13.         orderItem.ItemName = "T-shirt " + i;  
  14.         orderItem.Price = 100 + i;  
  15.         Order.items.Add(orderItem);  
  16.     }  
  17.     stringOrderDetail = Utility.RenderViewToString("Temp""~/Views/Shared/_OrderInvoice.cshtml", Order);  
  18.     SendEmailcode("OrderDetail", OrderDetail, "newUser@codeproject.com""dhruti@webmyne.com");  
  19.     return "success";  
  20. }  
Everything is done, now let's run the project.

wcf

After running the project "RenderViewtoString" will throw an error.

viewdetail

Something is missing. After reading the message I found that there is a need to install package for "Optimization".

Install-Package Microsoft.AspNet.Web.Optimization

After installation, Build project and Run. After this Integration I found this concept a life savor.