简体   繁体   English

MVC 4控制器和Web Api控制器

[英]MVC 4 Controller and Web Api controller

I am currently working on an MVC 4 project and i need to give acces to the database to the mobile apllication so i choosed to implement my Web services in Web Api to get a Json resulat . 我目前正在从事MVC 4项目,我需要为移动应用程序提供数据库访问权限,因此我选择在Web Api中实现我的Web服务以获得Json结果。 The problem is i have many code redundancy ! 问题是我有很多代码冗余! the same code is existent in MVC controller and in the Web Api controller . MVC控制器和Web Api控制器中存在相同的代码。

For exemple the get procedure : 例如,get程序:

1- web api controller : 1- Web api控制器:

 public User GetUser(int id)
    {
        User user = db.Users.Find(id);
        if (user == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

        return user;
    }

2-MVC controller 2-MVC控制器

 public ActionResult Details(int id = 0)
    {
        User user = db.Users.Find(id);
        if (user == null)
        {
            return HttpNotFound();
        }
        return View(user);
    }

one is returning the User entity in JSon and the other return a view ! 一个返回JSon中的User实体,另一个返回一个视图! So how can use one Controller in the other to get rid of redandency ? 那么如何在另一个控制器中使用一个控制器来消除冗余呢?

Looking at this question from the point of view of separation of concerns, both of the controllers have a different function (supplying JSON and markup respectively), but both need to make use of a common service: namely, data persistence. 从关注点分离的角度来看这个问题,两个控制器都有不同的功能(分别提供JSON和标记),但是两个控制器都需要使用通用服务:即数据持久性。

For that reason, as @paul suggested in the comments, the repository pattern offers a good design to solve this problem. 因此,正如@paul在评论中所建议的那样,存储库模式提供了解决此问题的良好设计。 In your example, you may not seem to gain much, but as soon as your data retrieval and persistence logic becomes more complex, the repository will enforce consistency, reduce redundancy, and support more sophisticated patterns such as dependency injection. 在您的示例中,您似乎并没有收获太多,但是一旦您的数据检索和持久性逻辑变得更加复杂,存储库就会强制执行一致性,减少冗余并支持诸如依赖注入之类的更复杂的模式。

Here's a simple repository: 这是一个简单的存储库:

interface IRepository
{
    User GetUser(int id);
}

public class MyRepository: IRepository
{
    public User GetUser(int id)
    {
        return db.Users.Find(id);
    }
}

Api controller api控制器

public User GetUser(int id)
{
    var repo = new MyRepository();
    User user = repo.GetUser(id);
    if (user == null)
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
    }
    return user;
}

MVC controller: MVC控制器:

public ActionResult Details(int id = 0)
{
    var repo = new MyRepository();
    User user = repo.GetUser(id);
    if (user == null)
    {
        return HttpNotFound();
    }
    return View(user);
}

As paul said this is all about separation of concerns. 正如保罗所说,这完全是关注点分离。 Paul provided you an example with a "logical service layer" which is an independent class library in your solution that your other Web Applications or desktop applications etc. reference it. Paul为您提供了一个带有“逻辑服务层”的示例,该逻辑层是您解决方案中的一个独立类库,您的其他Web应用程序或桌面应用程序等都引用了该库。 Another example may be a "physical service layer" which is another Web Api Project in your solution, that contains all the service methods of your application. 另一个示例可能是“物理服务层”,它是解决方案中的另一个Web Api项目,其中包含应用程序的所有服务方法。 From your MVC project whenever you want a call to have your users, you create a new WebClient to call your web api's GetUser end points. 在MVC项目中,只要您希望调用来吸引用户,就可以创建一个新的WebClient来调用Web api的GetUser端点。

You can just return JSON() from the MVC controller and avoid the usage of two frameworks. 您只需从MVC控制器返回JSON()即可避免使用两个框架。 There is nothing wrong with that, and will keep your life simple. 这没什么不对的,它将使您的生活变得简单。

public ActionResult GetUser(int id) // GetUser is the action name, or you can just use Index
{
    User user = db.Users.Find(id);
    if (user == null)
    {
        return HttpNotFound();
    }

    return Json(user);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM