C# 单独项目中MVC解决方案中的Web API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12905566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Web API in MVC solution in separate project
提问by amateur
I am creating a new MVC4 project, and research has lead me to believe that communicating from javascript to the server side is better achieved now through web API framework rather than controller actions. Is my understanding correct on this?
我正在创建一个新的 MVC4 项目,研究使我相信现在通过 Web API 框架而不是控制器操作可以更好地实现从 javascript 到服务器端的通信。我的理解是否正确?
I am presuming that I can share all my attributes etc between web API and MVC controllers so on the face it, it does not seem a massive change for me.
我假设我可以在 Web API 和 MVC 控制器之间共享我的所有属性等,所以从表面上看,这对我来说似乎不是一个巨大的变化。
When I am setting up applications, I like to split components out in to projects. My plan was to have a MVC project and a web API project. But I have ran in to issues. For example I have ended up with 2 apps as such, separate routing set up etc etc.
当我设置应用程序时,我喜欢将组件拆分为项目。我的计划是有一个 MVC 项目和一个 Web API 项目。但我遇到了问题。例如,我最终得到了 2 个应用程序,单独的路由设置等。
So my question is, in a MVC application should the web API framework sit within the same project, or should the web API be separated into a project of its own and work around the issues?
所以我的问题是,在 MVC 应用程序中,Web API 框架应该位于同一个项目中,还是应该将 Web API 分成自己的项目并解决这些问题?
采纳答案by Filip W
Unfortunately you are wrong about that - I am presuming that I can share all my attributes etc between web api and mvc controllers so on the face it, it does not seem a massive change for me.
不幸的是你错了 -我假设我可以在 web api 和 mvc 控制器之间共享我的所有属性等,所以从表面上看,这对我来说似乎不是一个巨大的变化。
Many of the concepts used by Web API and MVC, even though similar at first glance, are actually not compatible. For example, Web API attributes are System.Web.Http.Filters.Filterand MVC attributes are System.Web.Mvc.Filter- and they are not interchangeable.
Web API 和 MVC 使用的许多概念,尽管乍一看很相似,但实际上并不兼容。例如,Web API 属性System.Web.Http.Filters.Filter和 MVC 属性是System.Web.Mvc.Filter- 并且它们不可互换。
Same applies to many other concepts - model binding (completely different mechanisms), routes (Web API uses HTTPRoutes not Routes, even though they both operate on the same underlying RouteTable), dependency resolver (not compatible) and more - even though similar on the surface, are very different in practice. Moreover, Web API does not have a concept of areas.
这同样适用于许多其他概念——模型绑定(完全不同的机制)、路由(Web API 使用 HTTPRoutes 而不是路由,即使它们都在相同的底层 RouteTable 上运行)、依赖解析器(不兼容)等等——尽管在表面上看,实际操作上大相径庭。而且,Web API 没有区域的概念。
Ultimately, if all you are trying to do achieve is to have a "new, trendy" way of serving up JSON content - think twice before going down that path. I certainly wouldn't recommend refactoring any existing code unless you are really looking into embracing HTTP and building your app in a RESTful way.
最终,如果您想要实现的只是拥有一种“新的、时尚的”方式来提供 JSON 内容 - 在走这条路之前请三思。我当然不建议重构任何现有代码,除非您真的正在考虑采用 HTTP 并以 RESTful 方式构建您的应用程序。
It all really depends on what you are building. If you are starting a new project, and all you need is to serve up some JSON to facilitate your web app - provided you willing to live with some potentially duplicate code (like the stuff I mentioned above), Web API could easily be hosted within the same project as ASP.NET MVC.
这完全取决于您正在构建的内容。如果您正在开始一个新项目,并且您所需要的只是提供一些 JSON 以促进您的 Web 应用程序 - 如果您愿意接受一些可能重复的代码(如我上面提到的东西),Web API 可以很容易地托管在其中与 ASP.NET MVC 相同的项目。
I would only separate Web API into a separate project if you are going to build a proper API for your online service - perhaps to be consumed by external customers, or by various devices - such as fueling your mobile apps.
如果您打算为您的在线服务构建一个合适的 API,我只会将 Web API 分离到一个单独的项目中 - 可能由外部客户或各种设备使用 - 例如为您的移动应用程序提供燃料。
回答by Nick
Even if your project is so complex as to warrant two "front ends" then I would still only consider splitting out webapi into a separate project as a last resort. You will have deployment headaches and it would be difficult for a newbie to understand the structure of your solution. Not to mention routing issues.
即使您的项目如此复杂以至于需要两个“前端”,那么我仍然只会考虑将 webapi 拆分为一个单独的项目作为最后的手段。您会遇到部署难题,而且新手很难理解您的解决方案的结构。更不用说路由问题了。
I would aim to keep the system.web namespace isolated in the one "presentation layer". Despite the webapi not being presentationalit is still part of the interface of your application. As long as you keep the logic in your domain and not your controllers you should not run into too many problems. Also, don't forget to make use of Areas.
我的目标是将 system.web 命名空间隔离在一个“表示层”中。尽管 webapi 不是展示性的,但它仍然是应用程序界面的一部分。只要您将逻辑保留在您的域中而不是您的控制器中,您就不应该遇到太多问题。另外,不要忘记使用区域。
回答by David Peden
IMO, security and deployment should drive your decision. E.g., if your MVC app uses Forms authentication but you're interested in using Basic authentication (with SSL) for your API, separate projects are going to make your life easier. If you want to host yout site at www.example.com but host your API as api.example.com (vs. www.example.com/api), separate projects will make your life easier. If you separate your projects and subdomain them accordingly and you intend to leverage your own API from your MVC app, you will have to figure out how to deal with the Same Origin Policyissue for client-side calls to your API. Common solutions to this are to leverage jsonpor CORS(preferably if you can).
IMO、安全和部署应推动您的决定。例如,如果您的 MVC 应用程序使用表单身份验证,但您有兴趣为您的 API 使用基本身份验证(使用 SSL),单独的项目将使您的生活更轻松。如果您想在 www.example.com 上托管您的站点,但将您的 API 托管为 api.example.com(与 www.example.com/api),单独的项目将使您的生活更轻松。如果您将项目分开并相应地将它们划分为子域,并且您打算从您的 MVC 应用程序中利用您自己的 API,那么您将必须弄清楚如何处理客户端对 API 调用的同源策略问题。对此的常见解决方案是利用jsonp或CORS(如果可以,最好是)。
Update (3/26/2013): Official CORS support is coming: http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API
更新 (3/26/2013):官方 CORS 支持即将推出:http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API
回答by Jeroen K
Steven from SimpleInjector (IoC framework) advises two separate projects: What is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependencyResolver in WebAPI
来自 SimpleInjector(IoC 框架)的 Steven 建议了两个独立的项目:WebAPI 中的 DependencyResolver.SetResolver 和 HttpConfiguration.DependencyResolver 有什么区别
回答by fanvabra
I have recently done almost the same thing: I started with a new MVC 4 web application project choosing the Web API template in VS2012.
我最近做了几乎同样的事情:我从一个新的 MVC 4 Web 应用程序项目开始,选择了 VS2012 中的 Web API 模板。
This will create a Web API hosted in the same application as MVC.
这将创建一个托管在与 MVC 相同的应用程序中的 Web API。
I wanted to move the ApiControllers into a separate class library project. This was fairly easy but the solution was a bit hidden.
我想将 ApiControllers 移动到一个单独的类库项目中。这很容易,但解决方案有点隐藏。
In AssemblyInfo.cs of the MVC 4 project add similar line of code
在 MVC 4 项目的 AssemblyInfo.cs 中添加类似的代码行
[assembly: PreApplicationStartMethod(typeof(LibraryRegistrator), "Register")]
Now you need the class LibraryRegistrator (feel free to name it whatever)
现在你需要类 LibraryRegistrator(随意命名)
public class LibraryRegistrator
{
public static void Register()
{
BuildManager.AddReferencedAssembly(Assembly.LoadFrom(HostingEnvironment.MapPath("~/bin/yourown.dll")));
}
}
In the MVC 4 project also add reference to the Api library.
在 MVC 4 项目中还添加了对 Api 库的引用。
Now you can add Api controllers to your own separate class library (yourown.dll).
现在您可以将 Api 控制器添加到您自己的单独类库 (yourown.dll) 中。
回答by CularBytes
After some degree of experience (creating API for apps and for mvc). I mostly do both.
经过一定程度的经验(为应用程序和 mvc 创建 API)。我主要是两者都做。
I create a separate project for api calls that come from other clients or other devices (Android/IOS apps). One of the reasons is because the authentication is different, it is token based (to keep it stateless). I do not want to mix this within my MVC application.
我为来自其他客户端或其他设备(Android/IOS 应用程序)的 api 调用创建了一个单独的项目。原因之一是因为身份验证不同,它是基于令牌的(以保持无状态)。我不想在我的 MVC 应用程序中混合这个。
For my javascript/jquery api calls to my mvc application, I like to keep things simple so I include a web api inside my MVC application. I do not intend to have token based authentication with my javascript api calls, because hey, it's in the same application. I can just use [authorize]attribute on a API endpoint, when a user is not logged in, he will not get the data.
对于对我的 mvc 应用程序的 javascript/jquery api 调用,我喜欢保持简单,所以我在我的 MVC 应用程序中包含了一个 web api。我不打算对我的 javascript api 调用进行基于令牌的身份验证,因为嘿,它在同一个应用程序中。我可以只[authorize]在 API 端点上使用属性,当用户未登录时,他将无法获取数据。
Furthermore, when dealing with shopping carts and you want to store a users shopping cart in a session (while not logged in), you need to have this in your API as well if you add/delete products via your javascript code. This will make your API stateful for sure, but will also reduce the complexity in your MVC-API.
此外,当处理购物车并且您想在会话中存储用户购物车时(未登录时),如果您通过 JavaScript 代码添加/删除产品,您也需要在 API 中包含此内容。这肯定会使您的 API 有状态,但也会降低 MVC-API 的复杂性。
回答by jayson.centeno
In addition to setup the separate DLL for the Web.Api.
除了为 Web.Api 设置单独的 DLL。
Just a Suggestion:
只是一个建议:
- Create the Project
- Nugget WebActivatorEx
Create a a class Method to be called upon app_start
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(API.AppWebActivator),"Start")]
[assembly:WebActivatorEx.ApplicationShutdownMethod(typeof(API.AppWebActivator), "Shutdown")]
Register a web.api routes inside the Start Method
public static void Start() { GlobalConfiguration.Configure(WebApiConfig.Register); }
Reference the Project to the Web Project. to activate the Start Method.
- 创建项目
- Nugget WebActivatorEx
创建要在 app_start 上调用的类方法
[程序集:WebActivatorEx.PostApplicationStartMethod(typeof(API.AppWebActivator),"Start")]
[程序集:WebActivatorEx.ApplicationShutdownMethod(typeof(API.AppWebActivator), "Shutdown")]
在 Start 方法中注册一个 web.api 路由
public static void Start() { GlobalConfiguration.Configure(WebApiConfig.Register); }
将项目引用到 Web 项目。激活启动方法。
Hope this helps.
希望这可以帮助。
回答by jaicind
I tried to split the API controllers into a new project. All I've done is to create a new library project, moved the controllers inside folder named API. Then added the reference of the library project to the MVC project.
我试图将 API 控制器拆分为一个新项目。我所做的就是创建一个新的库项目,将控制器移动到名为 API 的文件夹中。然后将库项目的引用添加到MVC项目中。
The webAPI configuration is left in the MVC project itself. It works fine.
webAPI 配置保留在 MVC 项目本身中。它工作正常。

