Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET / ASP.NET5

Integration of MVC to WCF Service

5.00/5 (6 votes)
28 Dec 2015CPOL3 min read 30.3K   517  
MVC functionalities with web service with simple integration

Introduction

While working with the Android department for one of my projects, I found a problem while writing HTML tags in one string to format email properly. Then, I got the idea to format using the views that I am using for that project website, and started thinking of integration of WCF and MVC. Both projects are 100% ready, just one thing I was confident about was that using cshtml, I can format my mail for WCF. For other things, I would need to do R & D. After lots of errors and searching, I got the solution, which was pleasing.

Background

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

Using the Code

Let's start with magic. :)

First, create a WCF Service Application. You will see some basic Service and Interface creation.

Now, the Service Application is ready, and we need MVC Environment. For that, we will add MVC to Project using the Nuget Package Tool.

Image 1

Install-Package Microsoft.AspNet.Mvc -Version 5.2.3

Image 2

Now MVC and WCF is merged, but to work with MVC, three things are prerequisites and they are: Model, View, and Controller.

Let's start with View.

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

Image 3

For MVC Project, two web.config files are used. One at root level, and one inside the Views folder.

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

Image 4

MVC is working with Routing concept and for that it uses the Route.config file, so as MVC Structure will add first "App_Start" folder at root level. Then, we will add the Route.config file (copy it from any .NET MVC Project 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 the ".svc" extension.

Image 5

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

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

C#
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 below static method.

C#
public static string RenderViewToString(string controllerName, string viewName, object viewData)
        {
            using (var writer = new StringWriter())
            {
                var routeData = new RouteData();
                routeData.Values.Add("controller", controllerName);
                var fakeControllerContext = new ControllerContext
                (new HttpContextWrapper(new HttpContext(new HttpRequest
                (null, "http://google.com", null), new HttpResponse(null))), 
                routeData, new FakeController());
                var razorViewEngine = new RazorViewEngine();
                var razorViewResult = razorViewEngine.FindView
                (fakeControllerContext, viewName, "", false);

                var viewContext = new ViewContext(fakeControllerContext, 
                razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
                razorViewResult.View.Render(viewContext, writer);
                return writer.ToString();
            }
        }

For MVC Controller as the main part to work with this method, we need to add one controller. Let's name it as fakecontroller.

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

Now, all the ingredients are ready to cook for email. :)

Let's code for the Service method to Send Email where I will use View to string conversion method.

C#
string OrderDetail = Utility.RenderViewToString("Temp", "~/Views/Shared/_OrderInvoice.cshtml", Order);
C#
public string GetData()
        {
            OrderDetail Order = new OrderDetail();
            Order.OrderId = Guid.NewGuid();
            Order.OrderedOn = DateTime.Now;
            OrderItem orderItem = null;
            Order.items = new List<OrderItem>();
            for (int i = 0; i < 5; i++)
            {
                orderItem = new OrderItem();
                orderItem.ItemName = "T-shirt " + i;
                orderItem.Price = 100 + i;
                Order.items.Add(orderItem);
            }
            string OrderDetail = Utility.RenderViewToString
            ("Temp", "~/Views/Shared/_OrderInvoice.cshtml", Order);
            SendEmailcode("OrderDetail", OrderDetail, 
            "newUser@codeproject.com", "dhruti@webmyne.com");
            return "success";
        }

Everything is done, let's run Project.

Image 6

After running Project "RenderViewtoString" will throw an error. :(

Image 7

Something is missing ...

After reading the message, I found that I 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 saver.

Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)