ServiceStack与ASP.Net Web API [关闭]

本文翻译自:ServiceStack vs ASP.Net Web API [closed]

I want to write a new REST style API and have looked at ServiceStack and quite like it. 我想编写一个新的REST样式API并查看ServiceStack并且非常喜欢它。 However, I have seen that Microsoft has released the ASP.Net Web API project as part of the new MVC 4 beta. 但是,我已经看到Microsoft已经发布了ASP.Net Web API项目,作为新MVC 4 beta的一部分。 Has anyone looked at the new Web API project? 有没有人看过新的Web API项目? Can you give any pros/cons of each system? 你能给出每个系统的优缺点吗?


#1楼

参考:https://stackoom.com/question/ehAp/ServiceStack与ASP-Net-Web-API-关闭


#2楼

There is a new main difference that needs to be accounted for - ServiceStack is no longer free to use as of v4. 需要考虑一个新的主要区别 - 自v4起,ServiceStack不再可以自由使用。 Since there is a pretty definitive answer on the SS pro's I wanted to throw a couple out for Web API 由于SS专家有一个非常确定的答案,我想为Web API抛出一些

Web API Web API

Pro's : 专业人士:

  1. Free to use in your project (provided you have a VS license that allows commercial use) 免费在您的项目中使用(前提是您拥有允许商业用途的VS许可证)
  2. Extraordinarily high level of free support available from Microsoft and all over the web, including here on StackOverflow.com. Microsoft和整个网络提供的非常高级别的免费支持,包括StackOverflow.com。
  3. Quickly integrates with other Microsoft technology stacks like ASP.NET MVC which is extremely popular in Microsoft shops 快速集成其他Microsoft技术堆栈,如ASP.NET MVC,这在Microsoft商店中非常流行
  4. Built in support for RESTful authentication and authorization in your Microsoft stack 内置支持Microsoft堆栈中的RESTful身份验证和授权

Con's : Con's:

  1. Doesn't support SOAP 不支持SOAP

Ancillary Benefits 辅助福利

(Please feel free to leave comments below adding to why Web API has benefits or has pros / cons I can add) (请随时在下面留下评论,添加为什么Web API有好处或有我可以添加的优点/缺点)


#3楼

I can't really say much about ServiceStack, but Web API has a lot of great features and is currently at version 2. 我对ServiceStack说的不多,但Web API有很多很棒的功能,目前版本为2。

Some of the things you can do with Web API: 您可以使用Web API执行的一些操作:

  • Self host in an OWIN application (ie runs anywhere). 在OWIN应用程序中自托管(即在任何地方运行)。
  • Full support for async and await . 完全支持asyncawait
  • Good default Templates and tons of open source examples. 良好的默认模板和大量的开源示例。
  • Used great Json.Net JSON serializer. 使用了很棒的Json.Net JSON序列化器。
  • Rest-ish by default (you'll have to do hypermedia yourself). Rest-ish默认情况下(你必须自己做超媒体)。
  • and more... 和更多...

#4楼

As a customer of ServiceStack here is the pro for ServiceStack most important for me. 作为ServiceStack的客户,ServiceStack的专业人员对我来说最重要。

https://github.com/ServiceStack/Issues/issues/606 https://github.com/ServiceStack/Issues/issues/606

So. 所以。 Bug found, bug identified, bug fixed. 发现错误,发现错误,错误修复。 Same day. 同一天。 Extraordinary support! 非凡的支持!


#5楼

It's been one year that I use SS and it's all great. 我使用SS已经有一年了,这一切都很棒。 ORMLite is pure magic. ORMLite是纯粹的魔法。 I was able to remap an awfull MySQL DB to integrate in a mobile apps. 我能够重新映射一个可怕的MySQL数据库以集成到移动应用程序中。 No change on the database cause it's use with a php backend with another apps... 数据库没有变化导致它与另一个应用程序的php后端一起使用...

Mythz is an example regarding support and explanation. Mythz是关于支持和解释的一个例子。 It upgraded my knowledge regarding apps design and simplicity on maintenance. 它升级了我对应用程序设计和维护简单性的了解。 Please try it and you will understand. 请尝试一下,你会明白的。

Also, don't compare SS with WebAPI. 另外,不要将SS与WebAPI进行比较。 It's not enough, SS bring much more to your toolbox. 这还不够,SS为你的工具箱带来了更多。 ServiceStack.Text is a great Automapper too. ServiceStack.Text也是一个很棒的Automapper。


#6楼

They have very similar use-cases, as the lead maintainer for the ServiceStack project I have a good insight into ServiceStack's advantages and the many natural benefits of its message-based design . 它们具有非常相似的用例,作为ServiceStack项目的主要维护者,我很好地了解了ServiceStack的优势以及基于消息的设计许多自然优势

ServiceStack has been around since 2008 as an OSS-run project from its inception with a single goal of promoting the correct design and implementation of friction-free remote services. 自2008年以来,ServiceStack一直是OSS运行的项目,其目标是促进无摩擦远程服务的正确设计和实施。

Simple and Elegant Design 简约而优雅的设计

In its pursuit for ultimate simplicity, it's built around a simple and elegant core - with most of its features naturally binding to your models , not your controllers - which is what MVC, WebApi does (as well as every other Web Service Framework Microsoft has produced). 在追求极致简约的过程中,它围绕着一个简单而优雅的核心构建 - 其大部分功能自然地与您的模型绑定,而不是您的控制器 - 这就是MVA,WebApi所做的(以及Microsoft已生成的所有其他Web服务框架) )。

Adopting a message-based design offers a superior approach for remote services, in that they promote more extensible and less brittle services, simplifies access and calling patterns, and contain many other natural benefits you get for free . 采用基于消息的设计为远程服务提供了一种卓越的方法,因为它们可以促进更多可扩展和不易碎的服务,简化访问和调用模式,并包含免费获得的许多其他自然优势

As a core mission, we fight complexity at every stage, aiming to keep an invisible and non-intrusive API and avoid introducing any new concepts or artificial constructs that aren't already familiar to .NET or web service developers today. 作为核心任务,我们在每个阶段都要对抗复杂性,旨在保持隐形和非侵入式API,并避免引入任何当前.NET或Web服务开发人员尚不熟悉的新概念或人工构造。

As an example your IService<T> service implementation is just a standard C# class with auto-wired dependencies. 例如,您的IService<T>服务实现只是一个具有自动连线依赖关系的标准C#类。 Thin and lightweight wrappers are used to provide a consistent and unified API around the core run-time IHttpRequest and IHttpResponse types. 精简和轻量级的包装器用于围绕核心运行时IHttpRequestIHttpResponse类型提供一致且统一的API。 They also allow access to underlying ASP.NET or HttpListener's Request and Response classes so you're never restricted when using ServiceStack. 它们还允许访问底层的ASP.NET或HttpListener的Request和Response类,因此在使用ServiceStack时绝不会受到限制。

Contrasted with WCF and WebApi 与WCF和WebApi相比

Here's a brief overview of the contrasting API styles that ServiceStack and WCF promote . 以下是ServiceStack和WCF推广的对比API样式的简要概述。 WebApi is different to WCF in that it encourages REST-ful API design. WebApi与WCF的不同之处在于它鼓励REST-ful API设计。 As for examples between the 2, this is the only known example I have with the same service written in both ServiceStack and WebApi . 至于2之间的例子,这是我用ServiceStack和WebApi编写的相同服务的唯一已知示例。

Best Practices remote services 最佳实践远程服务

ServiceStack has a primary focus on simplicity, performance and in promoting web/remote service best-practices centered around embracing Martin Fowlers remote-service design patterns in as idiomatic C# as possible: ServiceStack主要关注简单性,性能和推广Web /远程服务最佳实践,主要围绕着Martin Fowlers远程服务设计模式,尽可能使用惯用的C#:

  • The Facade Pattern - Which suggests the usage of batchful, coarse-grained interfaces when ever you communicate across process boundaries. Facade模式 - 建议在跨进程边界进行通信时使用批量粗粒度接口。

  • The DTO pattern ( MSDN ) - Dictating the use of special-purpose POCOs to generate the wire format of your web services responses. DTO模式MSDN ) - 指示使用专用POCO生成Web服务响应的有线格式。

  • The Gateway Pattern ( MSDN ) to encapsulate your client and server communications between the Client Gateway / DTO models and Service Interface tiers. 网关模式MSDN ),用于封装客户端网关/ DTO模型和服务接口层之间的客户端和服务器通信。

These patterns ensure a clean separation of concerns and a friction-free iterative dev experience. 这些模式确保了关注点的清晰分离和无摩擦迭代开发体验。

Empowering your services 增强您的服务

A ServiceStack web service at its core is centered around a dependency-free and auto-wired pure C# IService<T> interface that gives you complete freedom to define your web service contract with your own Request and Response DTOs using clean POCOs - rendering ServiceStack's API practically invisible and non-invasive, ie it's trivial to extract your C# services logic and run it outside of a ServiceStack host. ServiceStack Web服务的核心是以无依赖和自动连接的纯C# IService<T>接口为中心,使您可以使用干净的POCO完全自由地使用自己的请求和响应DTO定义Web服务合同 - 呈现ServiceStack的API实际上是不可见和非侵入性的,即提取C#服务逻辑并在ServiceStack主机之外运行它是微不足道的。

This gist is a good example of what you get with just 1 C# .cs class in ServiceStack : 这个要点是ServiceStack中只有1个C#.cs类所得到的一个很好的例子:

  • Metadata pages for all registered formats 所有已注册格式的元数据页面
    • With links to WSDLs, XSDs and C# client examples 链接到WSDL,XSD和C#客户端示例
  • Human friendly HTML report view 人性化的HTML报告视图
    • A single self-contained html page snapshot (ie no external refs). 单个自包含的html页面快照(即没有外部引用)。 Includes embedded JSON web service response - allows programmatic access to data snapshots. 包括嵌入式JSON Web服务响应 - 允许以编程方式访问数据快照。
  • Built-in Mini Profiler (port of the excellent MVC Mini Profiler ) 内置Mini Profiler(优秀的MVC Mini Profiler的端口)
    • Includes Sql Profiling 包括Sql分析
  • JSON/JSONP, XML, JSV, CSV and SOAP end-points JSON / JSONP,XML,JSV,CSV和SOAP端点

The RestServiceBase and ServiceBase classes are intended to host your custom C# logic for maximum potential re-use as possible, eg Its DTO-first design trivially allows for deferred and proxied execution where your same C# Service can also be hosted and executed in an MQ Host which is what happens when you register an IMessageService like the RedisMQ host and call your service via the /asynconeway endpoint (ie client.SendOneWay() in C# Clients) RestServiceBase和ServiceBase类旨在托管您的自定义C#逻辑,以便尽可能地重复使用,例如,它的DTO优先设计通常允许延迟和代理执行,其中您的同一C#服务也可以在MQ主机中托管和执行当您注册像RedisMQ主机这样的IMessageService并通过/asynconeway端点(即C#客户端中的client.SendOneWay()调用您的服务时会发生什么?

You can also easily delegate and create composite services using the base.ResolveService<T>() method which returns an auto-wired instance of the selected service as seen in the Nortwind CustomerDetails Service example: 您还可以使用base.ResolveService<T>()方法轻松委派和创建组合服务,该方法返回所选服务的自动连接实例,如Nortwind CustomerDetails服务示例中所示:

var ordersService = base.ResolveService<OrdersService>();
var ordersResponse = (OrdersResponse)ordersService.Get(
    new Orders { CustomerId = customer.Id });

Return plain C# objects 返回普通的C#对象

For the most part ServiceStack will serialize most C# objects as expected - here's a list of possible return types ( from this answer ): 在大多数情况下,ServiceStack将按预期序列化大多数C#对象 - 这是可能的返回类型列表( 来自此答案 ):

  • Any DTO object -> serialized to Response ContentType 任何DTO对象 - >序列化为Response ContentType
  • HttpResult, HttpError, CompressedResult (IHttpResult) for Customized HTTP response 用于自定义HTTP响应的HttpResult,HttpError,CompressedResult(IHttpResult)

The following types are not converted and get written directly to the Response Stream: 以下类型未转换并直接写入响应流:

  • String
  • Stream
  • IStreamWriter IStreamWriter
  • byte[] - with the application/octet-stream Content Type. byte [] - 使用application / octet-stream内容类型。

An example of the Custom HTTP headers support can be seen by this CORS example where you can configure HTTP Headers globally or on a per-service basis. 此CORS示例可以看到自定义HTTP标头支持的示例 ,您可以在其中全局或基于每个服务配置HTTP标头。

HTML Support HTML支持

There are multiple options for returning HTML in ServiceStack that is explained in detail here . 在ServiceStack中有多个返回HTML的选项,这将在此处详细说明

Includes fastest text and binary serializers for .NET 包括.NET的最快文本和二进制序列化程序

Resilient and fast serializers are of primary importance in an API to ensure fast response times and a versionable API which doesn't break existing clients which is why ServiceStack includes the fastest text serializers for .NET with a NuGet option to enable @marcgravell 's Protocol Buffers (.NET's fastest binary serializer). 弹性和快速序列化器在API中是最重要的,以确保快速响应时间和版本化API,不会破坏现有客户端,这就是为什么ServiceStack包含最快的.NET文本序列化器,带有NuGet选项以启用@marcgravell协议缓冲区 (.NET最快的二进制序列化程序)。

ServiceStack's text serializers are very resilient and can withstand extreme versioning without error. ServiceStack的文本序列化程序非常有弹性,可以承受极端版本而不会出错。

Friction-free dev experience End-to-End 无摩擦开发体验端到端

ServiceStack's opinionated nature allows for a fast, typed, terse web service API end-to-end with built-in support for Sync/Async C#/.NET and Async Silverlight clients without any code-gen: ServiceStack的固执性质允许端到端的快速,类型化,简洁的Web服务API,内置支持Sync / Async C#/ .NETAsync Silverlight客户端,无需任何代码:

Sync C# Example 同步C#示例

var response = client.Send<HelloResponse>(new Hello { Name = "World!" });

Async C# Example 异步C#示例

client.SendAsync<HelloResponse>(new Hello { Name = "World!" },
    r => Console.WriteLine(r.Result), (r, ex) => { throw ex; });

As it just returns pure JSON it's also trivially consumed with other HTTP Clients, eg JS client example using jQuery : 因为它只返回纯JSON,所以它也很容易被其他HTTP客户端使用例如使用jQuery的JS客户端示例

$.getJSON("http://localhost/Backbone.Todo/todos", function(todos) {
    alert(todos.length == 1);
});

Highly testable 高度可测试

All C#/.NET ServiceClients share the same interfaces which make them highly testable and swappable to the point where you can have the same unit test also serve as an XML, JSON, JSV, SOAP Integration Test . 所有C#/ .NET ServiceClient共享相同的接口,这使得它们具有高度可测试性和可交换性,以至于您可以使用相同的单元测试作为XML,JSON,JSV,SOAP集成测试

Rich Validation and Error Handling built-in 内置丰富的验证和错误处理

In its mission to provide a friciton-free and clean dev experience, ServiceStack also includes typed validation and error handling built-in where throwing an C# Exception or using its built-in Fluent validation provides clients structured, typed errors easily accessible on web service clients, eg: 为了提供免费且干净的开发体验,ServiceStack还包括内置的类型验证和错误处理 ,其中抛出C#异常或使用其内置的Fluent验证,可以在Web服务客户端上轻松访问客户端结构化的类型错误,例如:

try {
    var client = new JsonServiceClient(BaseUri);
    var response = client.Send<UserResponse>(new User());
} catch (WebServiceException webEx) {
    /*
      webEx.StatusCode  = 400
      webEx.ErrorCode   = ArgumentNullException
      webEx.Message     = Value cannot be null. Parameter name: Name
      webEx.StackTrace  = (your Server Exception StackTrace - if DebugMode is enabled)
      webEx.ResponseDto = (your populated Response DTO)
      webEx.ResponseStatus   = (your populated Response Status DTO)
      webEx.GetFieldErrors() = (individual errors for each field if any)
    */
}

To make it trivial to consume errors in JavaScript, you can use the lightweight ss-validation.js JavaScript library to trivially bind your response errors to your HTML form fields with a single line of code. 为了在JavaScript中消除错误变得微不足道,您可以使用轻量级的ss-validation.js JavaScript库通过一行代码将响应错误简单地绑定到HTML表单字段。 The SocialBootstrapApi example project provides a good demo of this. SocialBootstrapApi示例项目提供了一个很好的演示。

Rich Integration with ASP.NET and MVC 与ASP.NET和MVC的丰富集成

The ServiceStack MVC PowerPack re-writes and fixes a lot of the ails of ASP.NET and MVC with replacements for its crippling Session and Caching XML-encumbered ASP.NET providers with its own clean and dependency-free implementation of ICacheClient and ISession APIs. ServiceStack MVC PowerPack重新编写并修复了ASP.NET和MVC的许多问题,并通过其自身干净且无依赖性的ICacheClient和ISession API实现替换其严重的Session和缓存XML加密的ASP.NET提供程序。

ServiceStack also includes a newer and cleaner authentication and autorization provider model with a number of different AuthProviders in-built: ServiceStack还包括一个更新,更干净的身份验证和自动化提供程序模型,其中包含许多内置的AuthProvider:

  • Credentials - For authenticating with username/password credentials by posting to the /auth/credentials service 凭据 - 通过发布到/ auth /凭证服务来使用用户名/密码凭证进行身份验证
  • Basic Auth - Allowing users to authenticate with Basic Authentication 基本身份验证 - 允许用户使用基本身份验证进行身份验证
  • Twitter OAuth - Allow users to Register and Authenticate with Twitter Twitter OAuth - 允许用户注册和使用Twitter进行身份验证
  • Facebook OAuth - Allow users to Register and Authenticate with Facebook Facebook OAuth - 允许用户注册和使用Facebook进行身份验证

The Authentication module is entirely optional and is built-on the clean ICacheClient / ISession APIs and OrmLite which allows your Sessions to be stored in Memory, Redis or Memcached and your UserAuth info persisted in OrmLite's supported RDBMS's of SQLServer, MySql, PostgreSQL, Sqlite as well as Redis data-store or InMemory (useful for dev/testing). Authentication模块完全是可选的,并且内置了干净的ICacheClient / ISession API和OrmLite,它允许您的Sessions存储在Memory,Redis或Memcached中,并且您的UserAuth信息保存在OrmLite支持的SQLServer,MySql,PostgreSQL,Sqlite的RDBMS中。以及Redis数据存储或InMemory(对开发/测试很有用)。

Great Documentation 伟大的文档

ServiceStack is very well documented where most of the information about the framework is hosted on the GitHub wiki . ServiceStack有很好的文档记录,其中大部分有关框架的信息都托管在GitHub wiki上 Documentation for other parts of the framework (eg Serializers, Redis, OrmLite) can be found on servicestack.net/docs/ 可以在servicestack.net/docs/上找到该框架其他部分的文档(例如Serializers,Redis,OrmLite)。

The ServiceStack.Examples Project provides the source code for all of ServiceStack's live demos and Starter Templates whilst the SocialBoostsrapApi project provides a great starting point of developing a Backbone.js Single Page App with ServiceStack and MVC based on Twitters Bootstrap template. ServiceStack.Examples项目为所有ServiceStack的现场演示和入门模板提供源代码,而SocialBoostsrapApi项目提供了一个很好的起点,可以使用基于Twitters Bootstrap模板的ServiceStack和MVC开发Backbone.js单页面应用程序。

In addition to the above a treasure trove of information is contained within the Google Group which has expanded quite considerably in recent years. 除了上述内容之外, 谷歌集团包含了一大堆信息,近年来这一信息已经大大扩展。

Runs Everywhere 到处运行

ServiceStack is a .NET 3.5 framework that runs on ASP.NET and HttpListener hosts and can be hosted on either .NET or Mono (trivia: www.servicestack.net is powered by CentOS/Mono). ServiceStack是一个.NET 3.5框架,可在ASP.NET和HttpListener主机上运行,​​可以托管在.NET或Mono上(琐事: www.servicestack.net由CentOS / Mono提供支持)。 This allows your ServiceStack web services to be hosted on either: 这允许您的ServiceStack Web服务托管在:

Windows with .NET 3.5 & 4.0 Windows 3.5和4.0

Linux/OSX with Mono 带有Mono的Linux / OSX

  • Apache + mod_mono Apache + mod_mono
  • Nginx + MonoFastCGI Nginx + MonoFastCGI
  • XSP XSP
  • Console App 控制台应用

Developed with the Open Source development model 使用开源开发模型开发

ServiceStack is a strong believer of the Open Source development model where it is actively developed in the open and has always been hosted under a liberal OSS licence (New BSD) since its inception. ServiceStack是开源开发模型的坚定信徒,它在开放时积极开发,自开始以来一直以自由OSS许可 (New BSD)为主。 As of today it has received contributions from more than 47 developers and it currently stands at the 3rd most watched C# project on GitHub . 截至今天,它已收到超过47位开发者的贡献,目前它是GitHub上第三个最受关注的C#项目

Disadvantages 缺点

I believe the biggest disadvantage is the same for most other OSS .NET projects where it wasn't developed (or even listed as an available option) by Microsoft. 我认为最大的缺点是大多数其他OSS .NET项目都没有,因为微软没有开发(甚至列为可用选项)。 This means it's rarely ever the first choice when evaluating a framework. 这意味着在评估框架时,它很少成为首选。 Most adopters will only evaluate ServiceStack as a last resort, where they're either frustrated with the imposed friction and brittleness of WCF or the performance of the preferred Microsoft Stack. 大多数采用者只会评估ServiceStack作为最后的手段,他们要么对WCF的强制摩擦和脆弱性或首选Microsoft Stack的性能感到沮丧。

Feedback and Community Resources 反馈和社区资源

ServiceStack has been very well received with positive feedback provided by most people who have evaluated it as visible by the positive sentiment in the mailing group . ServiceStack得到了很好的响应,大多数人都提供了积极的反馈,他们通过邮件组的积极情绪对其进行了评估。 As of this year the @ServiceStack twitter account has been tracking mentions and feedback in its favorites . 截至今年, @ ServiceStack Twitter帐户一直在跟踪其收藏夹中的提及和反馈

The Community Resources wiki page is a good place to find out more about ServiceStack in the wild with links to Blog Posts, Pod Casts, Presentations, Gists and more. 社区资源维基页面是一个了解更多有关ServiceStack的好地方,其中包含博客帖子,播客,演示文稿,Gists等链接。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值