C# RESTful Web 服务自动生成 WADL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12968007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:08:18  来源:igfitidea点击:

RESTful web service auto-generate WADL

c#auto-generatewadl

提问by David Poxon

I have created a RESTful web service in C# and have deployed it to IIS. When I access the service HeadOffice.svc, I have the option to view the WSDL (HeadOffice.svc?wsdl). What I would like to do is have the option of viewing the WADL (e.g. HeadOffice.svc?wadl). Is this possible?

我已经在 C# 中创建了一个 RESTful Web 服务并将其部署到 IIS。当我访问服务 HeadOffice.svc 时,我可以选择查看 WSDL (HeadOffice.svc?wsdl)。我想要做的是可以选择查看 WADL(例如 HeadOffice.svc?wadl)。这可能吗?

I have read around the place that the general opinion is that this is not the best practice. However, I need the WADL for a school assignment, so any help would be much appreciated.

我读过周围的地方,普遍认为这不是最佳实践。但是,我需要 WADL 来完成学校作业,因此非常感谢您的帮助。

采纳答案by Regfor

Suppose you already know that WADL is not standard / not supported widely. And when somebody needs WADL, may be then better to use WS*/SOAP service + WSDL. So your task looks like very strange.

假设您已经知道 WADL 不是标准的/没有得到广泛支持。当有人需要 WADL 时,最好使用 WS*/SOAP 服务 + WSDL。所以你的任务看起来很奇怪。

Anyway WADL is not supported "out of the box" in any REST implementation from Microsoft, neither WCF 3.5 Rest Starter Kit, neither WCF 4 REST, and ASP.NET WebAPI.

无论如何,Microsoft 的任何 REST 实现都不支持“开箱即用”的 WADL,WCF 3.5 Rest Starter Kit、WCF 4 REST 和 ASP.NET WebAPI 都不支持。

There are no reliable tools for WADL for .NET.

.NET 的 WADL 没有可靠的工具。

When your goal is to generate C# client code using WADL, believe me, you will spend more time as writing client code by yourself. And there are better solutions for that.

当您的目标是使用 WADL 生成 C# 客户端代码时,相信我,您会花更多时间自己编写客户端代码。并且有更好的解决方案。

You can use new classes like HttpClientclass or RestSharpor similar libraries to easily manually write your client and it will be even faster then googling for reliable WADL solution for .NET

您可以使用诸如HttpClient类或RestSharp或类似库之类的新类来轻松地手动编写您的客户端,它甚至会比谷歌搜索可靠的 .NET WADL 解决方案更快

Similar question on stackoverflow: Restful service in .NET with WADL instead of WSDL

stackoverflow 上的类似问题:Restful service in .NET with WADL 而不是 WSDL

UPDATE - Swagger:For some years swaggerhas established itself as such format. You can either start writing service definition using swagger's YAML in the Swagger editoror let generate swagger from existing services, for .NET using Swashbucklelibrary. The second is something we had with WSDL, and swagger editor let's you generate client and server boilerplates. Regardless you are generating your server or client or not fan of it, swagger is actually a very good contract exchange format for REST service, not ideal but good option.

更新 - Swagger:多年来,swagger已经确立了这种格式。您可以在Swagger 编辑器中使用 swagger 的 YAML 开始编写服务定义,也可以使用Swashbuckle库为 .NET 从现有服务生成 swagger 。第二个是我们在 WSDL 中拥有的东西,并且 swagger 编辑器让您生成客户端和服务器样板。无论您是生成服务器或客户端还是不喜欢它,swagger 实际上是一种非常好的 REST 服务合同交换格式,不是理想但不错的选择。

回答by Abhimanyu

Why Swagger4Wcf

为什么 Swagger4Wcf

?Manually writing yaml description for swagger and maintain it especially WCF services are boring.

?手动为swagger编写yaml描述并维护它,尤其是WCF服务很无聊。

?There is a nuget package called Swagger4WCF that automatically generates yaml description for swagger 2.0 for each interface matching attributes used by WCF (ServiceContract/OperationContract/WebGet/WebInvoke).

?有一个名为 Swagger4WCF 的 nuget 包,它为 WCF 使用的每个接口匹配属性自动生成 swagger 2.0 的 yaml 描述(ServiceContract/OperationContract/WebGet/WebInvoke)。

2. How Swagger Works in the Background

2. Swagger 如何在后台工作

Swagger4WCF uses NuPack post build pattern to trigger at build time.

Swagger4WCF 使用 NuPack 后期构建模式在构建时触发。

https://www.codeproject.com/Tips/1190360/How-to-setup-a-managed-postbuild-without-scripting

https://www.codeproject.com/Tips/1190360/How-to-setup-a-managed-postbuild-without-scripting

  1. At build time, it will detect assemblies present in output directory, open them with mono.cecil (to reflect assemblies) to generate expected yaml description for swagger 2.0. Swagger4WCF detects WebGet/WebInvoketo provide Verb/Method in serialization style in yaml.
  1. 在构建时,它将检测输出目录中存在的程序集,使用 mono.cecil(以反映程序集)打开它们以生成 swagger 2.0 的预期 yaml 描述。Swagger4WCF 检测WebGet/WebInvoke以在 yaml 中以序列化样式提供 Verb/Method。

Steps to implement Swagger in your application:

在您的应用程序中实现 Swagger 的步骤:

  1. Install SwaggerWcf package

  2. Configure WCF routes

  1. 安装 SwaggerWcf 包

  2. 配置 WCF 路由

We have to add the route in the Application_Start method inside Global.asax

我们必须在 Global.asax 中的 Application_Start 方法中添加路由

 protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.Add(new ServiceRoute("v1/rest", new WebServiceHostFactory(), typeof(BookStore)));
        RouteTable.Routes.Add(new ServiceRoute("api-docs", new WebServiceHostFactory(), typeof(SwaggerWcfEndpoint)));
    }

Note: Edit Web.config and add the following (if it doesn't exist yet) inside the system.serviceModel block

注意:编辑 Web.config 并在 system.serviceModel 块中添加以下内容(如果尚不存在)

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  1. Configure WCF response auto types (optional)
  1. 配置 WCF 响应自动类型(可选)

We have to add the following to Web.config. This will allow the WCF service to accept requests and send replies based on the Content-Type headers.

我们必须将以下内容添加到 Web.config。这将允许 WCF 服务接受请求并根据 Content-Type 标头发送回复。

   <behavior name="webHttpBehavior">
              <webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true"/>
            </behavior>
          </endpointBehaviors>
          <serviceBehaviors>
            <behavior>
              <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
  1. Decorate WCF services interfaces For each method, we have to configure the WebInvoke or WebGet attribute, and add a SwaggerWcfPath attribute.

    [SwaggerWcfPath("Get book", "Retrieve a book from the store using its id")] [WebGet(UriTemplate = "/books/{id}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] Book ReadBook(string id);

  2. Decorate WCF services class

  1. 装饰 WCF 服务接口 对于每个方法,我们都必须配置 WebInvoke 或 WebGet 属性,并添加一个 SwaggerWcfPath 属性。

    [SwaggerWcfPath("Get book", "Retrieve a book from the store using its id")] [WebGet(UriTemplate = "/books/{id}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] Book ReadBook(string id);

  2. 装饰 WCF 服务类

? Add the SwaggerWcf and AspNetCompatibilityRequirements attributes to the class providing the base path for the service.

? 将 SwaggerWcf 和 A​​spNetCompatibilityRequirements 属性添加到为服务提供基本路径的类。

? For each method, add the SwaggerWcfTag to categorize the method and theSwaggerWcfResponse for each possible response from the service.

? 对于每个方法,添加 SwaggerWcfTag 以对方法进行分类,并为来自服务的每个可能的响应添加 SwaggerWcfResponse。

[SwaggerWcfTag("Books")]
[SwaggerWcfResponse(HttpStatusCode.OK, "Book found, value in the response body")]
[SwaggerWcfResponse(HttpStatusCode.NoContent, "No books", true)]
public Book[] ReadBooks()
{
}
  1. Decorate data types used in WCF services

    [DataContract] [Description("Book with title, first publish date, author and language")] [SwaggerWcfDefinition(ExternalDocsUrl = "http://en.wikipedia.org/wiki/Book", ExternalDocsDescription = "Description of a book")]

    public class Book
    {
        [DataMember]
        [Description("Book ID")]
        public string Id { get; set; }
    
        [DataMember]
        [Description("Book Title")]
        public string Title { get; set; }
    
        [DataMember]
        [Description("Book First Publish Date")]
        public int FirstPublished { get; set; }
    
        [DataMember]
        [Description("Book Author")]
        public Author Author { get; set; }
    
        [DataMember]
        [Description("Book Language")]
        public Language Language { get; set; }
    }
    
  1. 修饰 WCF 服务中使用的数据类型

    [DataContract] [Description("Book with title, first publish date, author and language")] [SwaggerWcfDefinition(ExternalDocsUrl = "http://en.wikipedia.org/wiki/Book", ExternalDocsDescription = "Description of a book")]

    public class Book
    {
        [DataMember]
        [Description("Book ID")]
        public string Id { get; set; }
    
        [DataMember]
        [Description("Book Title")]
        public string Title { get; set; }
    
        [DataMember]
        [Description("Book First Publish Date")]
        public int FirstPublished { get; set; }
    
        [DataMember]
        [Description("Book Author")]
        public Author Author { get; set; }
    
        [DataMember]
        [Description("Book Language")]
        public Language Language { get; set; }
    }
    

Reference:- https://github.com/abelsilva/swaggerwcf

参考:- https://github.com/abelsilva/swaggerwcf

That's it wcf for Swagger implemented. Please free if you face any issue.

这就是 Swagger 实现的 wcf。如果您遇到任何问题,请免费。

Thanks, Abhi

谢谢,阿比