I am programming an API that would be used by both a web app and a mobile app and I am using ASP.NET MVC 2 in my technology stack.
Currently, I have an Rest-like API service which returns data in JSON format.
This works well for the mobile app, but I also want to make it work for the web app as well.
Would having the controller action return either a HTML View or JsonResult be a good approach for this?
The only difference between the web app and the mobile app is the view layer; the app logic is the same.
I guess I could create a controller that is used for the web app, but I think the a lot of logic would be duplicated from the API controller.
Edit
I do have another layer that handles all the app logic, but the API controller still has some logic to validate the parameters and error handling when it returns the JSON response. The duplicate logic so far would be the validation part.
Here is 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 = "..."});
}
}
I’ve seen one action method return both before, but, in my opinion, you are better off having two separate action methods. You can have them both call off to another method with the shared code, but since they are used for two very different things, you might find it is easier to maintain if you have two methods (a future requirement might cause one to change in a way that makes it difficult to support both in a single method).
Whether they are in the same controller or not is really more dependent on the nature, size, and complexity of the application. I have separated the API as a completely different project from the HTML. I have shared dlls for accessing the data and other common functions, but the MVC projects are different.