如何使用Visual Studio 2017从swagger docs生成restful api

时间:2017-04-14 23:53:22

标签: c# swagger visual-studio-2017

所以我正在使用Visual Studio 2017 Enterprise,前几天我注意到你可以右键单击并添加文件添加restful api client。所以我出去为我的休息服务生成了.json文件。我的Visual Studio生成了一堆类和文件。但是,我不明白如何使用这些类?

创建一个对象来调用我的restful后端方法的示例代码是什么?

我想也许这是我需要使用的对象,但是如果它们不能为null,那么ServiceClientCredentials是什么?

public AngularDemoComplete(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
    {
        if (credentials == null)
        {
            throw new ArgumentNullException("credentials");
        }
        this.Credentials = credentials;
        if (this.Credentials != null)
        {
            this.Credentials.InitializeServiceClient(this);
        }
    }

2 个答案:

答案 0 :(得分:0)

我仍在努力找出一个完整的解决方案,但我确实设法通过传递这些参数来实现这一点:

(new TokenCredentials("<bearer token>"), null)

不幸的是,我真的不明白这意味着什么。我在一篇关于使用autorest客户端的帖子中发现了这一点,它似乎生成了类似的代码:https://dzimchuk.net/generating-clients-for-your-apis-with-autorest/

我将继续解决这个问题,并会在我了解更多信息后对此进行更新。

您的任何更新都将不胜感激。

干杯

此外,我通过注释凭证参数的空检查来实现它。但这可能是不可取的。有趣的是,如果不需要身份验证,它可以在没有凭据的情况下工作。

更新:我发现有两种其他类型的凭证似乎更加自我解释:

  • BasicAuthenticationCredentials
  • CertificateCredentials

显然,使用TokenCredentials,您需要在此步骤之前从服务器获取令牌。如果使用OAuth,可能需要这样做。 由于我最初不需要身份验证,因此我将使用BasicAuthenticationCredentials而不设置UserName和Password属性。

答案 1 :(得分:0)

令我惊讶的是,没有更多的示例来说明如何使用https://github.com/Azure/AutoRest创建的生成代码,因此我认为值得在此处添加一些内容。

@Keiran的

+10,用于引用BasicAuthenticationCredentials,事实证明,它扩展了BasicAuthenticationCredentials,因此可以按以下方式使用:

BasicAuthenticationCredentials credentials = new BasicAuthenticationCredentials();
credentials.UserName = "joe@bloggs.com.au";
credentials.Password = "passwordvalue";
System.Uri baseUri = new System.Uri("https://api.something.com.au/v0.1/");
APIClassName client = new APIClassName(baseUri, credentials); 

APIClassNameSpace.Models.SomeResponse someResponse = client.GetSomething(requestHeaderParameter1, pathParameter1);

Visual Studio 2019当前会生成一个Models文件夹,其中包含swagger文件引用的所有类。它还产生其他三个类别,例如IAPIClassName,APIClassName,APIClassNameExtensions。使用API​​ClassName实例化客户端-swagger文件中指定的操作将自动完成。我并没有深入研究,但是带有前缀的类看起来像接口定义,带有扩展名的类看起来在于接口的实现。我的示例说明了请求标头参数和路径参数的用法,尽管该处理的实现是使用swagger文件中的详细信息生成的。

作为讨论的一部分,我必须提到How to handle both a single item and an array for the same property using JSON.net。处理JSON和为其生成代码的任何人都应该知道这一点!