Asp.Net MVC Using Web API to Return a Razor View

ASP.NEt MVC using Web API to return a Razor view

You could send an HTTP request to your Web API controller from within the ASP.NET MVC controller:

public class ProductController : Controller
{
public ActionResult Index()
{
var client = new HttpClient();
var response = client.GetAsync("http://yourapi.com/api/products").Result;
var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
return View(products);
}
}

Also if you can take advantage of the .NET 4.5 async/await it is strongly recommended to do so to avoid blocking calls:

public class ProductController : Controller
{
public async Task<ActionResult> Index()
{
var client = new HttpClient();
var response = await client.GetAsync("http://yourapi.com/api/products");
var products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
return View(products);
}
}

Problems trying to return the view with an API controller

You are having two different problems. Let's solve them separately.

1. Do I need to use ApiController or Controller?:

Someone already answered this here: Difference between ApiController and Controller in ASP.NET MVC.

The first major difference you will notice is that actions on Web API
controllers do not return views, they return data.

ApiControllers are specialized in returning data. For example, they
take care of transparently serializing the data into the format
requested by the client.

So, if you want to return a View you need to use the simple ol' Controller. The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage (View) for a user you don't use the Web API.

In other words, the Web API is about returning data to another service (to return a JSON or XML), not to a user.

2. But if I use Controller then I get "parameterless constructor" errors.

Okay, now we've got to your real problem. Don't try to reinvent the wheel and fight with ASP.NET about doing dependency injection! A tool already exists to resolve dependency injection and sort out the "parameterless constructor" error: Ninject.

If you're already using Ninject and still getting that error, you're doing something wrong with Ninject. Try to repeat the installation and configuration steps, and see some tutorials or questions about parameterless error with Ninject use

How to render view to string in ASP.NET MVC4 Api controller

You need to Install-Package RazorEngine using your NuGet console. Here is code that worked for me:

using RazorEngine;
using RazorEngine.Templating;

string razorTemplate = "Hello @Model!";
string html = Engine.Razor.RunCompile(
razorTemplate,
"uniqueTemplateKey", // Guid.NewGuid().ToString() for example
modelType: typeof(string),
model: "Lorem Ipsum");

Hope it helps!

Using WebAPI or MVC to return JSON in ASP.NET

Web API Controllers can be created and hosted in any ASP.NET Application, not just MVC applications. Thus, an obvious reason to create a Web API is if you do not have an MVC front-end (e.g. classic, RESTful web-services hosted by your company/organization.)

MVC Controllers typically rely on the MVC Framework, if you look at default templates and most of the work done by the community and your peers you will notice that almost all MVC Controllers are implemented with the View in mind.

Personally, I use MVC Controllers when I intend to respond with a View(), and I'll use a Web API for anything that isn't dependent on a particular view.

There are caveats, of course, but generally speaking if you don't require the Model Binding behavior of MVC, your service is data-centric, and operations are Data-centric (e.g. CRUD operations) then you likely want a 'Web API Controller' instead of a 'Model-View Controller'. Conversely, if your operations are View-centric (e.g. delivering a user admin page to the user), or you need MVC's Model Binding to generate 'ajax partials' (very unlikely), then you will want an MVC Controller instead.

Personally, I use Web API controllers for driving JSON-based RESTful clients, I use MVC controllers for handling basic browser routing and delivery of the SPA.



Related Topics



Leave a reply



Submit