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?
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With