I am programming an API to be used by both a web application and a mobile application, and I am using ASP.NET MVC 2 in my technology stack.
I currently have a Rest-like API service that returns data in JSON format. This works well for a mobile application, but I also want it to work for a web application as well.
Will the controller effect return either HTML View or JsonResult for this good approach?
The only difference between the web application and the mobile application is the presentation level; application logic is the same.
I think I could create a controller that is used for the web application, but I think that a lot of logic would be duplicated from the API controller.
Edit
I have another layer that handles all the application logic, but the API controller still has some logic for checking parameters and handling errors when it returns a JSON response. So far, duplicate logic has been part of the test.
Here are some code snippets:
public JsonResult GetList(string accessToken, string listId) { if (string.IsNullOrEmpty(accessToken)) return Json(new { success = false, exceptionMessage = "Facebook access token is required." }); if (string.IsNullOrEmpty(listId)) return Json(new { success = false, exceptionMessage = "The list id is required." }); string facebookId = null; var facebookIdParseSuccess = GetFacebookId(accessToken, out facebookId); if (!facebookIdParseSuccess) return Json(new { success = false, exceptionMessage = "There was a problem accessing your Facebook profile information." }); try { _groceryListManager.FacebookId = facebookId; var groceryList = _groceryListManager.GetList(listId); GroceryListViewModel mappedList = new GroceryListViewModel(); Mapper.Map(groceryList, mappedList); return Json(new { success = true, results = mappedList }); } catch (Exception ex) { return Json(new { success = false, exceptionMessage = "..."}); } }
source share