4

我对 RESTful 服务还很陌生,我刚刚实现了测试代码以使 ServiceStack RESTful 服务与 Swagger 插件一起工作,这让我想到了我的问题......

在 swagger-ui/index.html 中有一个“api_key”字段。我知道变量名是 umm... 变量,我也可以随意设置它,但我有点困惑它的用途以及我是否应该使用它。

另外,如果我确实使用它,servicestack 如何在服务器端向我呈现该值?

这是我从文档中启动并运行的测试服务...

    [Api("Hello Web Services")]    
    [Route("/Hello", Summary = @"Noel's ServiceStackSwagger thingy", Notes = "Some more info in here cause these are notes")]
    [Route("/Hello/{name}",   Summary = @"N031'5 ServiceStackSwagger thingy", Notes = "Some more info in here cause these are notes", Verbs="GET,POST" )] 
    public class Hello
    {
        [ApiMember(Name = "Name", Description = "This is a description", ParameterType = "path", DataType = "string", Verb="GET,POST")]
        public string Name { get; set; }
    }

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


    public class HelloService : Service
    {
        public object Any(Hello request)
        {
            return new HelloResponse { Result = "Hello, " + request.Name };
        }
    }
4

2 回答 2

4

回答我自己对 Esker 的跟进请求,这里是如何使用 API Key 的东西......

public class HelloService : Service
{        
    public object Any(Hello request)        
    {
        string api_key = this.Request.Headers["api_key"];            
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
} 

但还需要一些额外的 javascript 将其包含在标题中(在 swagger-ui/index.html 内)...

   $(function () {
        $.ajaxSetup({
            beforeSend: function (jqXHR, settings) {
                jqXHR.setRequestHeader("api_key", $("#input_apiKey").val());
            }
        });
    });

我在这个问题的答案中找到了...

如何让 Swagger 将 API 密钥作为 http 而不是在 URL 中发送

于 2013-08-14T09:14:57.040 回答
3

Swagger UI has a general concept of supplying an api_key to use in every request sent to your service, documented here. It can either be sent as a query string or header value, and you can also change the name of the parameter as described in the above link.

You only need to configure this if you actually do require an API key in your ServiceStack service (e.g. if you have a request filter that checks for and validates an API key, perhaps).

The reason you might need to configure a default API key value in the JavaScript code to set up Swagger instead of having the user type in an API key is that as soon the index.html page loads, it will send multiple requests to your service to retrieve the metadata, so it wants to know what API key value to send by default for these metadata requests before the user can begin to interact.

于 2013-08-13T12:12:10.177 回答