我正在构建一个小型测试工具,该工具应该为用户提供 Web 服务列表(使用 WebAPI 构建)。用户应该能够选择要测试的服务。 我正在使用
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://'localhost':51062/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
我正在寻找类似的东西
client.GetAllWebServices()
这将返回用户可以看到的方法列表。意思是,他在 Controller 上开发并想要测试的方法。
最佳答案
迈克尔正确地提到了 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 文档注释并不是那么明确,但有一个关于 MSDN Blogs 的教程.
此外,还有其他可用的软件包,您可以使用、 Hook 、窃取,例如,它们的功能与您需要的类似
有关这些的更多详细信息 in VS Mag
关于c# - 如何获取 WebAPI Web 服务中可用方法的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27267775/