Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unified MVC and Web Api - same controller for views and json?

One of the new features in visual studio 2015 (preview) is that "ASP.NET MVC and Web API... have been unified into a single programming model."

http://blogs.msdn.com/b/webdev/archive/2014/11/12/announcing-asp-net-features-in-visual-studio-2015-preview-and-vs2013-update-4.aspx

I assumed that this meant that I could write a single controller action "GetCustomerById", that returned a Customer object and that it could be rendered either as serialized Json or as Html (using an mvc view) based on content negotiation. (if the user requested it with "Accept: application/json" or "Accept: text/html")

But I cannot see how this can be done, they still seem to require different controller and methods?

like image 354
Bjorn Avatar asked Nov 18 '14 12:11

Bjorn


People also ask

Can a Web API controller return an MVC view?

You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.

Can I use MVC controller as Web API?

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.

Are MVC and Web API merged into one in mvc6?

ASP.NET MVC 6 comes with some new features as well. Some prominent ones are: - MVC, WEB API and Web Pages are merged into one single framework.


1 Answers

This can be done without the new unified model. In any MVC controller you can inspect the headers as well as the Request.IsAjaxRequest() method to determine whether how to return data.

Here is bare-bones simplified example of such a method:

internal ActionResult ReturnResultAsRequested(object result)
{
  if (Request.Headers["Accept"].Contains("application/json"))
    return Json(result);
  else if (Request.IsAjaxRequest())
    return PartialView(Request.RequestContext.RouteData.Values["Action"], result);
  else
    return View(Request.RequestContext.RouteData.Values["Action"], result);
}
like image 175
Jay Avatar answered Oct 01 '22 06:10

Jay