可以ASP.. NET自动从API定义文件生成代码?



在许多API (web服务)的Swagger页面上有一个文档文件,其中包含有关API对象属性的信息(它们的类型,是否需要等),似乎这些数据可以用于自动生成创建/读取/更新/删除代码或可能用于API服务的代码,用于与API端点的交互。

我想知道这是否可能在。net 6.0(或其他版本),Visual Studio Professional等。提前谢谢你。

首先,可以肯定的是,ASP.net完全可以实现API文档的自动生成。它可以满足后端接口的测试。步骤如下:

1。创建一个Web API项目

2。修改默认的API路由配置为什么要修改它?因为每个控制器的默认路由是分配给"api/{Controller}/{id}"的,所以生成的默认控制器类似如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebAPI.Controllers
{
public class ValuesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}

3。我们需要一个方法来提供多种HTTP访问方法,所以应该添加动作配置,比如:"api/{controller}/{action}/{id}"修改WebApiConfig.cs文件。代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace WebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API Routing
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

4。修改HelpPageConfig.cs文件,代码如下:

// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
using WebAPI.Utils;
namespace WebAPI.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "WebAPI.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
#region *************************XML display interface parameters and comments****************** ***********************            
// Add the XML configuration of this project or other reference projects: multiple can be added
config.SetDocumentationProvider(new MultiXmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/WebAPI.XML")));
#endregion
Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type 
formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
//    {typeof(string), "sample string"},
//    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
#region *************************Default JSON display interface******************** *********************            
//config.SetSampleForMediaType(
//    new TextSample("Binary JSON content. See http://bsonspec.org for details."),
//    new MediaTypeHeaderValue("application/bson"));
#endregion
Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
}

这个修改支持多种XML文档方法,扩展类如下:

using System;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebAPI.Areas.HelpPage;
using WebAPI.Areas.HelpPage.ModelDescriptions;
namespace WebAPI.Utils
{
/// <summary>A custom <see cref='IDocumentationProvider'/> that reads the API documentation from a collection of XML documentation files.</summary>
public class MultiXmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider
{
/*********
** Properties
*********/
/// <summary>The internal documentation providers for specific files.</summary>
private readonly XmlDocumentationProvider[] Providers;

/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name='paths'>The physical paths to the XML documents.</param>
public MultiXmlDocumentationProvider(params string[] paths)
{
this.Providers = paths.Select(p => new XmlDocumentationProvider(p)).ToArray();
}
/// <summary>Gets the documentation for a subject.</summary>
/// <param name='subject'>The subject to document.</param>
public string GetDocumentation(MemberInfo subject)
{
return this.GetFirstMatch(p => p.GetDocumentation(subject));
}
/// <summary>Gets the documentation for a subject.</summary>
/// <param name='subject'>The subject to document.</param>
public string GetDocumentation(Type subject)
{
return this.GetFirstMatch(p => p.GetDocumentation(subject));
}
/// <summary>Gets the documentation for a subject.</summary>
/// <param name='subject'>The subject to document.</param>
public string GetDocumentation(HttpControllerDescriptor subject)
{
return this.GetFirstMatch(p => p.GetDocumentation(subject));
}
/// <summary>Gets the documentation for a subject.</summary>
/// <param name='subject'>The subject to document.</param>
public string GetDocumentation(HttpActionDescriptor subject)
{
return this.GetFirstMatch(p => p.GetDocumentation(subject));
}
/// <summary>Gets the documentation for a subject.</summary>
/// <param name='subject'>The subject to document.</param>
public string GetDocumentation(HttpParameterDescriptor subject)
{
return this.GetFirstMatch(p => p.GetDocumentation(subject));
}
/// <summary>Gets the documentation for a subject.</summary>
/// <param name='subject'>The subject to document.</param>
public string GetResponseDocumentation(HttpActionDescriptor subject)
{
return this.GetFirstMatch(p => p.GetDocumentation(subject));
}

/*********
** Private methods
*********/
/// <summary>Get the first valid result from the collection of XML documentation providers.</summary>
/// <param name='expr'>The method to invoke.</param>
private string GetFirstMatch(Func<XmlDocumentationProvider, string> expr)
{
return this.Providers
.Select(expr)
.FirstOrDefault(p => !String.IsNullOrWhiteSpace(p));
}
}
}

注意:当XML文档注释启用时,HelpPageConfig.cs需要注释掉以下代码

#region *************************Default JSON display interface******************** *********************            
//config.SetSampleForMediaType(
//    new TextSample("Binary JSON content. See http://bsonspec.org for details."),
//    new MediaTypeHeaderValue("application/bson"));
#endregion

5。接下来,您可以编写一些Controller.cs。然后启动项目以查看Api链接。

6。配置自动生成接口测试页添加对NuGet安装包的引用:

WebApiTestOnHelpPage

7。点击"测试api";

相关内容

最新更新