ServiceStack REST API 和 CORS [英] ServiceStack REST API and CORS

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

问题描述

有谁知道是否可以使用ServiceStack框架来创建CORS REST服务?

Does anyone know if the ServiceStack framework can be used to create CORS REST services?

几天来,我一直在与 WCF REST 的东西碰撞 - 完全没用.

I've been banging my head against the WCF REST stuff for days now - utterly useless.

推荐答案

使用 CorsFeature 插件

启用全球 CORS 支持

我们现在有一个 CorsFeature,它将 CORS 标头包装到 插件中 可以更轻松地将 CORS 支持添加到您的 ServiceStack 服务.

Using the CorsFeature plugin

Enabling Global CORS support

We now have a CorsFeature which wraps CORS headers into the Plugin below to make it much easier to add CORS support to your ServiceStack services.

通常这就是现在所需要的:

Commonly this is now all that's needed:

Plugins.Add(new CorsFeature());

哪个使用默认值:

CorsFeature(allowedOrigins:"*", 
    allowedMethods:"GET, POST, PUT, DELETE, OPTIONS", 
    allowedHeaders:"Content-Type", 
    allowCredentials:false);

您可以省略任何与默认值匹配的值.例如.如果您只想将允许的方法限制为 GET 和 POST 请求,您可以这样做:

You can leave out any of the values matching the default. E.g. if you just wanted to restrict the allowed methods to just GET and POST requests, you can just do:

Plugins.Add(CorsFeature(allowedMethods:"GET, POST"));

为所有 OPTION 请求全局启用 CORS

注册 CorsFeature(或手动全局标头)后,您可以选择为所有 OPTION 请求启用 CORS,方法是添加 PreRequest 过滤器以发出所有注册的全局标头(即 CorsFeature 中的标头)) 并将所有 OPTIONS 请求短路:

Globally enable CORS for all OPTION requests

Once the CorsFeature (or manual Global Headers) is registered, you can optionally choose to enable CORS for all OPTION requests by adding a PreRequest filter to emit all registered Global Headers (i.e. the Headers in CorsFeature) and short-circuit all OPTIONS requests with:

this.PreRequestFilters.Add((httpReq, httpRes) => {
    //Handles Request and closes Responses after emitting global HTTP Headers
    if (httpReq.Method == "OPTIONS") 
        httpRes.EndRequest(); //add a 'using ServiceStack;'
});

启用 CORS 每服务支持

ServiceStack 还允许您使用 [EnableCors] 在每个服务的基础上启用 CORS,而不是使用上面的插件 响应过滤器属性,其默认值与上述相同.例如.您可以仅启用 GET、POST,如下所示:

Enabling CORS per-service support

Instead of using the plugin above, ServiceStack also allows you to enable CORS on a per-service basis by using [EnableCors] Response Filter attribute which has the same defaults as above. E.g. You can enable just GET, POST as above with:

[EnableCors(allowedMethods:"GET,POST")]
public class MyService : Service { ... }

手动启用 CORS

ServiceStack 的美妙之处在于它建立在高度灵活且简单的核心之上.我们不会尝试为所有内容构建强类型 API,因为无法预测未来会出现哪些新的 HTTP 标头/状态代码.因此,在我们提供方便的行为来完成常见任务的同时,我们还提供了一个灵活的 API,让您可以配置任何所需的 HTTP 输出.

Manually enabling CORS

The beauty of ServiceStack is that it's built on a highly flexible and simple core. We don't try to build strong-typed APIs over everything, as it's impossible to predict what new HTTP Headers / StatusCodes will exist in the future. So whilst we provide convenient behavior to accomplish common tasks, we also provide a flexible API that lets you configure any desired HTTP Output.

这是如何在您的 AppHost 配置中全局启用跨源共享:

This is how to globally enable Cross Origin Sharing in you AppHost config:

public override void Configure(Container container)
{
    //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
    base.SetConfig(new EndpointHostConfig
    {
        GlobalResponseHeaders = {
            { "Access-Control-Allow-Origin", "*" },
            { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
            { "Access-Control-Allow-Headers", "Content-Type" },
        },
    });
}

在服务中返回自定义 HTTP 标头

每个请求都会发送这些标头,或者您也可以为特定的 Web 服务启用它,即采用 Hello World Web 服务 例如:

public class Hello {
    public string Name { get; set; }
}

public class HelloResponse {
    public string Result { get; set; }
}

public class HelloService : IService 
{
    public object Any(Hello request)
    {
        var dto = new HelloResponse { Result = "Hello, " + request.Name };
        return new HttpResult(dto) {
            Headers = {
              { "Access-Control-Allow-Origin", "*" },
              { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" } 
              { "Access-Control-Allow-Headers", "Content-Type" }, }
        };
    }
}

以上是开发 Web 服务所需的所有 C# 代码,然后该服务会自动连接到所有 HTTP 动词(GET、POST 等)和内置端点,即 JSON、XML、JSV、HTML, CSV, SOAP 1.1/1.2 - 免费,无需任何配置或摩擦.查看上述网络服务的实例.

The above is all the C# code you need to develop a web service which is then automatically wired up for you on all HTTP Verbs (GET, POST, etc) and built-in endpoints, i.e. JSON, XML, JSV, HTML, CSV, SOAP 1.1/1.2 - for free, without any config or friction required. Checkout the live example of the above web service.

除了上述端点之外,每个服务都可以由 JSONP(另一种在 Ajax 应用程序中启用跨域服务调用的流行方法)调用,其中每个服务都可以通过 JSONP 调用,只需添加 ?callback=cb 参数给查询字符串,例如:

In addition to the above endpoints each service is available to be called by JSONP (another popular way to enable cross-domain service calls in Ajax apps) where each service can be called via JSONP by simply adding the ?callback=cb parameter to the querystring, e.g:

http://www.servicestack.net/ServiceStack.Hello/servicestack/hello/world?callback=cb

这是使用 ServiceStack 的灵活性和生产力胜利的另一个例子,您可以在 Web 服务中获得无摩擦的灵活性和表达自由,以字面上返回几乎任何内容 并按预期序列化.

This is another example of the flexibility and productivity wins of using ServiceStack where you're literally given friction-free flexibility and expressive freedom in your web service to literally return just about anything and it gets serialized as expected.

它不仅比 WCF 更容易使用(具有更多开箱即用的功能),而且在 其所有组件都经过高度优化以实现最佳性能.

It's not only easier to use than WCF (with more features out-of-the-box) but it's also much faster where all its components are highly optimized for maximum performance.

这篇关于ServiceStack REST API 和 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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