【问题标题】:How can I get a list of available methods in a WebAPI web service?如何获取 WebAPI Web 服务中可用方法的列表?
【发布时间】:2014-12-03 09:20:18
【问题描述】:

我正在构建一个小型测试工具,它应该为用户提供一个 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()

这将返回用户可以看到的方法列表。意思是,他在控制器上开发并想要测试的方法。

【问题讨论】:

  • 检查ApiExplorer,它可能会让你继续前进。
  • 这给了我这些:-methodInfos {System.Reflection.MethodInfo[43]} System.Reflection.MethodInfo[] + [0] {System.Net.Http.Headers.HttpRequestHeaders get_DefaultRequestHeaders()} System.Reflection.MethodInfo + [1] {System.Uri get_BaseAddress()} + [2] {Void set_BaseAddress(System.Uri)} + [3] {System.TimeSpan get_Timeout()} 等等......它没有提供开发者编写的方法,如“GetAllCustomers()”
  • Kobi 说它“不“知道”任何关于你的特定 API URL 的东西”似乎是对的。也许我应该使用其他东西而不是 HTTPClient?
  • 有什么例子可以将它用于一些通用的 REST api 吗?

标签: c# httpclient


【解决方案1】:

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

【讨论】:

  • 感谢恒宝!没有 d.ResponseDescription,但我不需要它。这比我预期的要多做一些工作,因为需要创建这个额外的控制器,但总比没有好,而且它可以工作!再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2012-05-29
  • 2011-01-05
  • 1970-01-01
  • 2010-11-28
相关资源
最近更新 更多