ServiceStack 与 ASP.Net Web API [英] ServiceStack vs ASP.Net Web API

查看:29
本文介绍了ServiceStack 与 ASP.Net Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个新的 REST 风格的 API,并且看过 ServiceStack 并且非常喜欢它.但是,我看到微软已经发布了 ASP.Net Web API 项目,作为新的 MVC 4 测试版的一部分.有没有人看过新的 Web API 项目?你能给出每个系统的优点/缺点吗?

I want to write a new REST style API and have looked at ServiceStack and quite like it. However, I have seen that Microsoft has released the ASP.Net Web API project as part of the new MVC 4 beta. Has anyone looked at the new Web API project? Can you give any pros/cons of each system?

推荐答案

他们有非常相似的用例,作为 ServiceStack 项目 我对 ServiceStack 的优势和 其基于消息的设计的许多自然优势.

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 自 2008 年以来一直是一个由 OSS 运行的项目,其单一目标是促进无摩擦远程服务的正确设计和实现.

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.

为了追求极致的简单性,它围绕一个简单而优雅的核心 - 它的大部分功能自然地绑定到您的模型,而不是您的控制器 - 这就是 MVC、WebApi(以及 Microsoft 生成的所有其他 Web 服务框架)所做的.

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).

采用基于消息的设计为远程服务提供了一种卓越的方法,因为它们促进了更可扩展和更脆弱的服务,简化了访问和调用模式,以及 包含您免费获得的许多其他自然好处.

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.

作为一项核心使命,我们在每个阶段都与复杂性作斗争,旨在保持一个不可见且非侵入性的 API,并避免引入任何新概念或人工构造,这些概念或人工构造对于 .NET 或 Web 服务开发人员而言目前尚不熟悉.

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.

例如,您的 IService 服务实现只是一个标准的 C# 类,具有自动连接的依赖项.轻量级包装器用于围绕核心运行时 IHttpRequestIHttpResponse 类型.它们还允许访问底层 ASP.NET 或 HttpListener 的请求和响应类,因此您在使用 ServiceStack 时永远不会受到限制.

As an example your IService<T> service implementation is just a standard C# class with auto-wired dependencies. Thin and lightweight wrappers are used to provide a consistent and unified API around the core run-time IHttpRequest and IHttpResponse types. They also allow access to underlying ASP.NET or HttpListener's Request and Response classes so you're never restricted when using ServiceStack.

这里简要概述了ServiceStack 和WCF 推广的对比API 样式.WebApi 与 WCF 的不同之处在于它鼓励 REST-ful API 设计.至于 2 之间的示例,这是我唯一已知的示例,其中使用 ServiceStack 和 WebApi.

Here's a brief overview of the contrasting API styles that ServiceStack and WCF promote. WebApi is different to WCF in that it encourages REST-ful API design. As for examples between the 2, this is the only known example I have with the same service written in both ServiceStack and WebApi.

ServiceStack 的主要重点是简单性、性能和推广网络/远程服务最佳实践,其中心是尽可能用惯用的 C# 来拥抱 Martin Fowlers 远程服务设计模式:

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:

  • 外观模式 - 建议使用批量、粗粒度的接口当您跨流程边界进行通信时.

  • The Facade Pattern - Which suggests the usage of batchful, coarse-grained interfaces when ever you communicate across process boundaries.

DTO 模式(MSDN) - 规定使用特殊用途的 POCO 来生成网络服务响应的有线格式.

The DTO pattern (MSDN) - Dictating the use of special-purpose POCOs to generate the wire format of your web services responses.

网关模式(MSDN) 来封装客户端网关/DTO 模型和服务接口层之间的客户端和服务器通信.

The Gateway Pattern (MSDN) to encapsulate your client and server communications between the Client Gateway / DTO models and Service Interface tiers.

这些模式确保了关注点的清晰分离和无摩擦的迭代开发体验.

These patterns ensure a clean separation of concerns and a friction-free iterative dev experience.

ServiceStack Web 服务的核心是一个无依赖且自动连接的纯 C# IService<T> 接口,让您可以完全自由地使用自己的请求定义 Web 服务合同和使用干净的 POCO 响应 DTO - 使 ServiceStack 的 API 几乎不可见且非侵入性,即提取您的 C# 服务逻辑并在 ServiceStack 主机之外运行它是微不足道的.

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, i.e. it's trivial to extract your C# services logic and run it outside of a ServiceStack host.

这个要点是一个很好的例子,说明您使用 ServiceStack 中的 1 个 C# .cs 类:

This gist is a good example of what you get with just 1 C# .cs class in ServiceStack:

  • 所有注册格式的元数据页面
    • 包含指向 WSDL、XSD 和 C# 客户端示例的链接
    • 一个独立的 html 页面快照(即没有外部引用).包括嵌入式 JSON 网络服务响应 - 允许以编程方式访问数据快照.
    • 包括 Sql 分析

    RestServiceBase 和 ServiceBase 类旨在托管您的自定义 C# 逻辑,以尽可能实现最大的潜在重用,例如它的 DTO 优先设计简单地允许延迟和代理执行,其中您的相同 C# 服务也可以在 MQ 主机中托管和执行,这就是当您注册 IMessageService 时发生的情况,例如 RedisMQ 主机 并通过 /asynconeway 端点调用您的服务(即client.SendOneWay() 在 C# 客户端)

    The RestServiceBase and ServiceBase classes are intended to host your custom C# logic for maximum potential re-use as possible, e.g. 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 (i.e. client.SendOneWay() in C# Clients)

    您还可以使用 base.ResolveService<T>() 方法轻松委托和创建复合服务,该方法返回所选服务的自动连接实例,如 Nortwind CustomerDetails Service 示例:

    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:

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

    返回普通的 C# 对象

    在大多数情况下,ServiceStack 将按预期序列化大多数 C# 对象 - 这是可能的返回类型列表(来自这个答案):

    • 任何 DTO 对象 -> 序列化为响应 ContentType
    • 用于自定义 HTTP 响应的 HttpResult、HttpError、CompressedResult (IHttpResult)

    以下类型未转换并直接写入响应流:

    The following types are not converted and get written directly to the Response Stream:

    • 字符串
    • IStreamWriter
    • byte[] - 带有应用程序/八位字节流内容类型.

    自定义 HTTP 标头支持的示例可以通过 这个 CORS 示例看到您可以在其中全局或按服务配置 HTTP 标头.

    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.

    ServiceStack 中有多种返回 HTML 的选项,即 此处详细解释.

    There are multiple options for returning HTML in ServiceStack that is explained in detail here.

    弹性和快速序列化程序在 API 中至关重要,以确保快速响应时间和不破坏现有客户端的可版本化 API,这就是为什么 ServiceStack 包含 最快的 .NET 文本序列化器,带有 NuGet 选项以启用 @marcgravell协议缓冲区(.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).

    ServiceStack 的文本序列化程序非常有弹性,可以承受极端版本控制而不会出错.

    ServiceStack's text serializers are very resilient and can withstand extreme versioning without error.

    ServiceStack 固执己见的特性允许端到端的快速、类型化、简洁的 Web 服务 API 以及对 同步/异步 C#/.NET异步 Silverlight客户端没有任何代码生成:

    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:

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

    异步 C# 示例

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

    因为它只返回纯 JSON,所以它也很容易与其他 HTTP 客户端一起使用,例如使用 jQuery 的 JS 客户端示例:

    As it just returns pure JSON it's also trivially consumed with other HTTP Clients, e.g. JS client example using jQuery:

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

    高度可测试

    所有 C#/.NET ServiceClient 共享相同的接口,这使它们高度可测试 并且可以交换到您可以将相同的单元测试 也用作 XML、JSON、JSV、SOAP 集成测试.

    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.

    为了提供无摩擦和干净的开发体验,ServiceStack 还包括 类型化验证和内置错误处理,其中抛出 C# 异常或使用其内置的 Fluent 验证为客户端提供结构化、类型化的错误,可在 Web 服务客户端上轻松访问,例如:

    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, e.g:

    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)
        */
    }
    

    为了避免在 JavaScript 中处理错误,您可以使用轻量级的 ss-validation.js JavaScript 库,使用一行代码轻松地将您的响应错误绑定到您的 HTML 表单字段.SocialBootstrapApi 示例项目 提供了一个很好的演示.

    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. The SocialBootstrapApi example project provides a good demo of this.

    ServiceStack MVC PowerPack 重写并修复了 ASP 的许多问题.NET 和 MVC 替换其 残缺的会话和缓存 XML-encumbered ASP.NET 提供程序,使用它自己干净且无依赖的 ICacheClient 和 ISession API 实现.

    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 还包括一个更新和更清晰的身份验证和授权提供程序模型内置了许多不同的 AuthProvider:

    ServiceStack also includes a newer and cleaner authentication and autorization provider model with a number of different AuthProviders in-built:

    • 凭据 - 用于通过发布到/auth/credentials 服务来使用用户名/密码凭据进行身份验证
    • 基本身份验证 - 允许用户使用基本身份验证进行身份验证
    • Twitter OAuth - 允许用户在 Twitter 上注册和验证
    • Facebook OAuth - 允许用户注册 Facebook 并进行身份验证

    身份验证模块完全是可选的,并且建立在干净的 ICacheClient/ISession API 和 OrmLite 之上,它允许您的会话存储在内存、Redis 或 Memcached 中,并且您的 UserAuth 信息保存在 OrmLite 支持的 SQLServer、MySql、PostgreSQL 的 RDBMS 中、Sqlite 以及 Redis 数据存储或 InMemory(用于开发/测试).

    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).

    ServiceStack 有很好的文档记录,其中关于框架的大部分信息都托管在 GitHub wiki.框架其他部分(例如序列化程序、Redis、OrmLite)的文档可以在 servicestack.net/docs/<上找到/a>

    ServiceStack is very well documented where most of the information about the framework is hosted on the GitHub wiki. Documentation for other parts of the framework (e.g. Serializers, Redis, OrmLite) can be found on servicestack.net/docs/

    ServiceStack.Examples 项目为所有 ServiceStack 的现场演示和 Starter 提供源代码模板,而 SocialBoostsrapApi 项目 为开发具有 ServiceStack 和 MVC 的 Backbone.js 单页应用程序提供了一个很好的起点基于 Twitter 引导程序模板.

    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.

    除上述之外,还有一个信息宝库包含在 Google 群组中 近年来发展相当迅速.

    In addition to the above a treasure trove of information is contained within the Google Group which has expanded quite considerably in recent years.

    ServiceStack 是一个 .NET 3.5 框架,运行在 ASP.NET 和 HttpListener 主机上,可以托管在 .NET 或 Mono 上(琐事:www.servicestack.net 由 CentOS/Mono 提供支持).这允许您的 ServiceStack Web 服务托管在:

    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). This allows your ServiceStack web services to be hosted on either:

    • IIS 5/6/7 (uses IHttpHandler)
    • VS.NET WebDevServer
    • Console App or Windows GUI
    • Windows Service
    • Apache + mod_mono
    • Nginx + MonoFastCGI
    • XSP
    • 控制台应用

    ServiceStack 是开源开发模型的坚定拥护者,它在开放中积极开发,并且始终托管在 自由 OSS 许可证(新 BSD)自成立以来.截至今天,它已收到超过 47 个开发人员的贡献,目前位于 GitHub 上第三个最受关注的 C# 项目.

    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. 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.

    我相信对于大多数其他 OSS .NET 项目来说,最大的缺点是相同的,因为它不是由 Microsoft 开发的(或者甚至列为可用选项).这意味着在评估框架时,它很少是首选.大多数采用者只会将 ServiceStack 评估为最后的手段,他们要么对 WCF 强加的摩擦和脆弱性感到沮丧,要么对首选的 Microsoft Stack 的性能感到沮丧.

    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. 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 受到了很好的接受,大多数人都提供了积极的反馈,他们将其评价为通过 邮件组中的积极情绪.截至今年,@ServiceStack 推特帐户一直在跟踪 在其收藏夹中提及和反馈.

    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. As of this year the @ServiceStack twitter account has been tracking mentions and feedback in its favorites.

    社区资源 wiki 页面是了解更多关于野外 ServiceStack 包含指向博客文章、播客广播、演示文稿、要点等的链接.

    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 与 ASP.Net Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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