Michael 提到ApiExplorer 是正确的。这将为您提供所有 WebApi 方法的详细信息。你只需要按照你想要的响应来格式化它。
这是一个简单的示例,用于获取所有方法及其参数和返回类型的列表。您当然可以使这更加全面 - 只需浏览对象以找到您需要的内容:
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
namespace WebApplication1.Controllers
{
public class ApiMethodController : ApiController
{
public IEnumerable<HelpMethod> GetMethods()
{
// get the IApiExplorer registered automatically
IApiExplorer ex = this.Configuration.Services.GetApiExplorer();
// loop, convert and return all descriptions
return ex.ApiDescriptions
// ignore self
.Where(d => d.ActionDescriptor.ControllerDescriptor.ControllerName != "ApiMethod")
.Select(d =>
{
// convert to a serializable structure
return new HelpMethod
{
Parameters = d.ParameterDescriptions.Select(p => new HelpParameter
{
Name = p.Name,
Type = p.ParameterDescriptor.ParameterType.FullName,
IsOptional = p.ParameterDescriptor.IsOptional
}).ToArray(),
Method = d.HttpMethod.ToString(),
RelativePath = d.RelativePath,
ReturnType = d.ResponseDescription.DeclaredType == null ?
null : d.ResponseDescription.DeclaredType.ToString()
};
});
}
}
public class HelpMethod
{
public string Method { get; set; }
public string RelativePath { get; set; }
public string ReturnType { get; set; }
public IEnumerable<HelpParameter> Parameters { get; set; }
}
public class HelpParameter
{
public string Name { get; set; }
public string Type { get; set; }
public bool IsOptional { get; set; }
}
}
好处是它本身就是一个WebApi调用,所以你可以使用HttpClient来调用和处理它使用http://www.localhost.com/api/ApiMethod/Methods。这是一个示例 JSON 响应:
[
{
"Method": "GET",
"RelativePath": "api/Account/{id}",
"ReturnType": "WebApplication1.Models.Account",
"Parameters": [
{
"Name": "id",
"Type": "System.Int32",
"IsOptional": false
}
]
},
{
"Method": "POST",
"RelativePath": "api/Account",
"ReturnType": null,
"Parameters": [
{
"Name": "a",
"Type": "WebApplication1.Models.Account",
"IsOptional": false
}
]
},
{
"Method": "GET",
"RelativePath": "api/Maths?i={i}&j={j}",
"ReturnType": "System.Int32",
"Parameters": [
{
"Name": "i",
"Type": "System.Int32",
"IsOptional": false
},
{
"Name": "j",
"Type": "System.Int32",
"IsOptional": false
}
]
}
]
继续前进
获取 XML doc cmets 不是很明确,但是在 MSDN Blogs 上有一个教程。
此外,还有其他可用的包可供您使用、挂钩、窃取,例如,它们的功能与您需要的类似
更多详情in VS Mag