什么是“api_key”以及如何正确使用它

Nin*_*oel 5 c# rest servicestack swagger

我对 Restful 服务相当陌生,我刚刚实现了测试代码,以获得与 Swagger 插件一起工作的 ServiceStack Restful 服务,这引出了我的问题......

在 swagger-ui/index.html 中有一个“api_key”字段。我知道变量名称是嗯...变量,我也可以将其设置为任何我喜欢的内容,但我有点困惑它的用途以及我是否应该使用它。

另外,如果我确实使用它,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 };
        }
    }
Run Code Online (Sandbox Code Playgroud)

Nin*_*oel 5

为了回答我自己的 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 };
    }
} 
Run Code Online (Sandbox Code Playgroud)

但还需要一些额外的 javascript 将其包含在标头中,如下所示(在 swagger-ui/index.html 内)...

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

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

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