ASP.NET MVC:让 API 控制器操作返回视图和/或 JSON 是个好习惯吗?
我正在编写一个可供 Web 应用程序和移动应用程序使用的 API,并且我在我的技术堆栈中使用 ASP.NET MVC 2。
目前,我有一个类似 Rest 的 API 服务,它以 JSON 格式返回数据。 这对于移动应用程序来说效果很好,但我也想让它也适用于网络应用程序。
让控制器操作返回 HTML View 或 JsonResult 是一个好方法吗?
Web 应用程序和移动应用程序之间的唯一区别是视图层;应用程序逻辑是相同的。
我想我可以创建一个用于 Web 应用程序的控制器,但我认为很多逻辑会从 API 控制器中重复。
编辑
我确实有另一个层来处理所有应用程序逻辑,但 API 控制器仍然有一些逻辑来验证参数和返回 JSON 响应时的错误处理。到目前为止,重复的逻辑是验证部分。
这是一些代码片段:
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 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 = "..."});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
取决于您确切想要实现的目标:
创建一个返回正确视图的 ViewEngine
示例: http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilityViewEngine.aspx
或者,您可以根据 URL 中的参数返回 View 或 JSON
Depending what you exactly want to achieve:
Create a ViewEngine which returns the correct View
example: http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilitiesViewEngine.aspx
alternatively you can return a View or JSON depending on a parameter in the URL
我想你自己回答了这个问题。我会把它们放在同一个控制器中。 :)
I think you answered the question yourself. I would keep them in the same controller. :)
如果您的视图模型也适合以 JSON 形式返回,那么在同一操作中执行这两项操作效果会很好。类似于:
这也有助于引导您进入使用渐进增强的成功深渊。如果 HTML 和 JSON 的 URL 相同,那么在标记中使用可访问/SEO 友好的 URL 会容易得多,然后通过添加不显眼的事件处理程序来逐步增强,以在支持 JavaScript 的浏览器中将其替换为 JSON 请求。
If your view's model is suitable for returning as JSON too, doing both in the same action can work well. Something like:
This also helps guide you into the pit of success in terms of using progressive enhancement. If the URL for HTML and JSON is the same, it's that much easier to use accessible/SEO-friendly URLs in your markup and then progressively enhance by adding unobtrusive event handlers to replace that with requests for the JSON in JavaScript-enabled browsers.
我以前见过一种操作方法同时返回两个方法,但是,在我看来,最好有两个单独的操作方法。您可以让它们都使用共享代码调用另一个方法,但由于它们用于两个截然不同的事情,您可能会发现如果您有两个方法,维护起来会更容易(未来的需求可能会导致其中一个方法发生变化)这使得很难用单一方法同时支持这两种方法)。
它们是否位于同一个控制器中实际上更取决于应用程序的性质、大小和复杂性。我已将 API 作为一个与 HTML 完全不同的项目分开。我有用于访问数据和其他常用功能的共享 dll,但 MVC 项目不同。
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.