.NET Core解决方案中同时具有API和MVC项目的约定 [英] Conventions on having both an API and MVC project in .NET Core solution

查看:71
本文介绍了.NET Core解决方案中同时具有API和MVC项目的约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由以下项目构成的ASP.NET Core(.NET Core 2.2)应用程序:

I have an ASP.NET Core (.NET Core 2.2) app structured with the following projects:

  • API:这是为了表示WebAPI(带有继承自 ControllerBase 的控制器)
  • 服务:其中包含API控制器用来访问数据库等的服务
  • 数据库:其中包含常用的数据库存储库,服务层可利用这些数据库访问数据库

现在,我想添加一个与API对话的UI(MVC部分位于.NET核心之前)..NET Core如何实现这一点,而MVC和WebAPI是同一件事?MVC控制器/模型/视图是否应包含在API中?它应该是一个在其他端口上侦听的新项目吗?身份验证如何同时适用于这两种方式(例如,API通常具有一些基于令牌的身份验证,UI应用程序通常具有用户名/密码身份验证)?WebAPI和MVC部分是否应该像ASP.NET Identity一样共享相同的身份验证?如果他们使用相同的数据库,那会不会紧密地结合在一起?

Now, I want to add a UI that talks to the API (the MVC part pre-.NET-core). How is that accomplished with .NET Core, where MVC and WebAPI are one of the same thing? Should MVC controllers/models/views be part of the API? Should it instead be a new project that listens on a different port? How does authentication fit in for both (e.g. APIs usually have some token-based authentication, UI apps usually have username/password authentication)? Should the WebAPI and MVC portions share the same authentication like ASP.NET Identity? Wouldn't that tightly couple the two if they use the same database?

是否有某种Microsoft或社区建议的约定/文档说明如何构建此类项目?

Is there some kind of Microsoft or community suggested convention/documentation for how to structure such projects?

推荐答案

使用MVC和WebAPI是同一件事的.NET Core如何做到这一点?

在dotnet核心中,MVC和WebAPI可以存在于同一项目中.一切应用程序都像控制台应用程序.您可以将MVC服务添加到启动类中,以使其成为MVC应用程序.

In dotnet core MVC and WebAPI can be present in the same project. Everything application is like a console application. You can add MVC services to startup class to make it an MVC application.

MVC控制器/模型/视图是否应成为API的一部分?

最好将与MVC和WebAPI相关的功能分别使用不同的控制器,同时将它们保存在同一文件夹中.

Its better to have different controllers for MVC and WebAPI related functions separately while keeping them in the same folder.

模型-它们可同时用于mvc和webapi.视图模型和DTO相同.

Models - They can be reused for both mvc and webapi. Same for view models and DTOs.

视图-仅对于MVC,webapi不需要视图.

Views - Just for MVC, webapi does not require views.

应该是一个在其他端口上侦听的新项目吗?

是的,您可以为webapi和MVC创建一个不同的项目.

Yes, you can create a different project for webapi and MVC.

身份验证如何同时适用于两者(例如,API通常具有一些基于令牌的身份验证,UI应用程序通常具有用户名/密码身份验证)?

如果您使用基于令牌的身份验证,则Web API和MVC都将可以使用.

If you use token-based authentication then both web API and MVC will be able to use.

WebAPI和MVC部分是否应该像ASP.NET Identity一样共享相同的身份验证?如果他们使用相同的数据库,那会不会紧密地结合在一起?

如果将ASP.Net Identity与身份服务器一起使用,则MVC和webapi将能够共享相同的身份验证机制而无需紧密耦合.

If you use ASP.Net Identity with identity server then both MVC and webapi will be able to share the same authentication mechanism without tightly coupling.

这篇关于.NET Core解决方案中同时具有API和MVC项目的约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆