我正在构建一个小型测试工具,它应该为用户提供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"));
Run Code Online (Sandbox Code Playgroud)
我正在寻找类似的东西
client.GetAllWebServices()
Run Code Online (Sandbox Code Playgroud)
这将返回用户可以看到的方法列表.意思是,他在控制器上开发并想要测试的方法.
Rhu*_*orl 15
迈克尔是正确的提及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; }
}
}
Run Code Online (Sandbox Code Playgroud)
好处是它本身就是一个WebApi调用,因此您可以使用http://www.localhost.com/api/ApiMethod/MethodsHttpClient来调用和处理它.这是一个示例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
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
往前走
获取XML文档注释并不是那么明确,但MSDN博客上有一个教程.
此外,还有其他可用的包,例如,您可以使用,挂钩,偷取,类似于您需要的包
关于VS Mag的更多细节
| 归档时间: |
|
| 查看次数: |
13744 次 |
| 最近记录: |