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 the web API ... were combined 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 represented as serialized Json or as Html (using the mvc view) based on content negotiation. (if the user requested it using "Accept: application / json" or "Accept: text / html")

But I don’t see how this can be done, do they still need different controllers and methods?

+6
source share
1 answer

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

The following is an example of a simplified example:

 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); } 
0
source

Source: https://habr.com/ru/post/978328/


All Articles