列表控制器和类Asp.NET网站的API [英] List Of Controllers And Classes In Asp.NET Web API

查看:173
本文介绍了列表控制器和类Asp.NET网站的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要访问我的Web API的所有控制器。比方说,我有2个控制器和2班;

I want to access all of controllers in my web api. Let's say I have 2 controllers and 2 classes;

string fooId

string fooName

酒吧

string barId

string barName

Sample1Controller

Get(int fooId)

Post([FromBody] Foo foo)

Sample2Controller

Get(int barId)

Post([FromBody] Bar bar)

我想列出我的控制器,具有属性Foo和酒吧类的。我怎样才能做到这一点?

I want to list of my controllers, Foo and Bar class with properties. How can I do this ?

更新

我想创建移动应用程序请求和响应类。例如,如果我远程访问这些细节,我可以为Java或Objective-C的请求和响应类。

I want to create request and response classes for mobile apps. For example If I access these details remotely, I can create request and response classes for java or objective-c.

推荐答案

您可以使用 ApiExplorer 类,这是专为生成的Web API的文档类。

You could use the ApiExplorer class which is a class specifically designed to generate documentation for Web APIs.

通常的用它来生成HTML帮助页面,但没有什么可以阻止你创造一个更加机器可读的输出如JSON或XML。如果通过API操作方法揭露输出你会得到要么取决于就像任何其他的API方法所要求的类型。

Typically it is used to generate HTML help pages but there is nothing to stop you creating a more machine readable output such as JSON or XML. If you expose the output via an API action method you will get either depending on the requested type just like any other API method.

有是创造一个帮助页面<一个好文章href=\"http://blogs.msdn.com/b/yaohuang1/archive/2012/05/13/asp-net-web-api-introducing-iapiexplorer-apiexplorer.aspx\">here但没有对周围的比输出HTML的任何其他多的材料。不幸的是,ApiExplorer类是不可序列化,所以你不能只是一个调用的结果返回到 GetApiExplorer()但它足以琐碎,创造我们自己的类是序列化,填充他们,然后从API返回的行动者。

There is a good article on creating a help page here but there isn't much material around about outputting anything other than HTML. Unfortunately the ApiExplorer classes are not serializable so you can't just return the result of a call to GetApiExplorer() but it's trivial enough to create our own classes that are serializable, populate them and then return those from an API action.

您可以使用 GlobalConfiguration.Configuration.Services.GetApiExplorer()访问 ApiExplorer 类。ApiDescriptions 。这将返回一个收集和LT; ApiDescription&GT; 其中包含控制器,动作和参数信息。它甚至可以被用于从任何访问文档///摘要意见,如果你愿意的话。这取决于你是什么样的信息后是什么格式,你想在,但下面的是什么,你可以用这种方法实现的例子:

You can access the ApiExplorer classes by using GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions. That will return a Collection<ApiDescription> which contains information on the controllers, actions and parameters. It can even be used to access documentation from any ///summary comments if you so desire. It depends on what information you are after and what format you would like that in but the below is an example of what you can achieve using this method:

首先我创建了一个类来存储操作方法的详细信息:

Firstly I've created a class to store the Action method details:

[DataContract]
public class ActionMethod
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public List<Parameter> Parameters { get; set; }
    [DataMember]
    public string SupportedHttpMethods { get; set; }
}

请注意, SupportedHttpMethods 只是一个字符串而非列表&LT; T&GT; 。您可能要提高,要在列表&LT; T&GT; ,但在这个例子中,我只是逗号分隔它们使生活的的容易

Note that the SupportedHttpMethods is just a string rather than a List<T>. You may want to improve that to a List<T> but for this example I'm just comma separating them to make life slightly easier.

ActionMethod 类有一个列表&LT;参数&GT; 看起来像这样:

The ActionMethod class has a List<Parameter> which looks like this:

[DataContract]
public class Parameter
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Source { get; set; } //where we pass the parameter when calling the action
    [DataMember]
    public string Type { get; set; }
    [DataMember]
    public List<Parameter> SubParameters { get; set; }

}

请注意,子参数是存储类型的成员变量的复杂类型。我只捕获一个层次深,但如果需要,它会很容易扩展这一点。

Note that the SubParameters is for storing the types of member variables for complex types. I'm only capturing one level deep but it would be easy enough to extend this if required.

然后,我创建了一个新的控制器与操作方法将返回我们的API信息作为列表&LT; ActionMethod&GT; 。请注意,我已经添加的属性 [ApiExplorerSettings(IgnoreApi = TRUE)] 它告诉 ApiExplorer 忽略任何东西这个控制器所以我们没有产生我们的文档化控制器上的文件(将工作,但它太元对我来说!)。

Then, I've created a new Controller with an action method that will return our API information as a List<ActionMethod>. Note that I've added the attribute [ApiExplorerSettings(IgnoreApi = true)] which tells the ApiExplorer to ignore anything in this Controller so we don't generate documentation on our documenting controller (that would work, but it's too meta for me!).

[ApiExplorerSettings(IgnoreApi = true)]
public class HelpController : ApiController
{
    public List<ActionMethod> Get()
    {
        var apiActions = new List<ActionMethod>();

        Collection<ApiDescription> apiDescriptions = GlobalConfiguration
                           .Configuration
                           .Services
                           .GetApiExplorer()
                           .ApiDescriptions;

        foreach (var api in apiDescriptions)
        {
            List<Parameter> parameters = new List<Parameter>();
            //get the parameters for this ActionMethod
            foreach (var parameterDescription in api.ParameterDescriptions)
            {
                Parameter parameter = new Parameter()
                {
                    Name = parameterDescription.Name, 
                    Source = parameterDescription.Source.ToString(),
                    Type = parameterDescription.ParameterDescriptor.ParameterType.ToString(),
                    SubParameters = new List<Parameter>()
                };
                //get any Sub-Parameters (for complex types; this should probably be recursive)
                foreach (var subProperty in parameterDescription.ParameterDescriptor.ParameterType.GetProperties())
                {
                    parameter.SubParameters.Add(new Parameter()
                    {
                        Name = subProperty.Name,
                        Type = subProperty.PropertyType.ToString()
                    });
                }

                parameters.Add(parameter);
            }
            //add a new action to our list
            apiActions.Add(new ActionMethod()
            {
                Name = api.ActionDescriptor.ControllerDescriptor.ControllerName,
                Parameters = parameters, 
                SupportedHttpMethods = string.Join(",", api.ActionDescriptor.SupportedHttpMethods)
            });
        }

        return apiActions;
    }
}

我们可以接着在 / API /帮助访问API文档。有了你给作为你的问题的例子控制器和动作方法,要求JSON给出这样的回应:

We can then access the api documentation at /api/help. With the controller and action methods you give as an example in your question, asking for JSON gives a response like this:

[
   {
      "Name":"Bar",
      "Parameters":[
         {
            "Name":"barId",
            "Source":"FromUri",
            "Type":"System.Int32",
            "SubParameters":[

            ]
         }
      ],
      "SupportedHttpMethods":"GET"
   },
   {
      "Name":"Bar",
      "Parameters":[
         {
            "Name":"bar",
            "Source":"FromBody",
            "Type":"ApiTest.Controllers.Bar",
            "SubParameters":[
               {
                  "Name":"barId",
                  "Source":null,
                  "Type":"System.String",
                  "SubParameters":null
               },
               {
                  "Name":"barName",
                  "Source":null,
                  "Type":"System.String",
                  "SubParameters":null
               }
            ]
         }
      ],
      "SupportedHttpMethods":"POST"
   },
   {
      "Name":"Foo",
      "Parameters":[
         {
            "Name":"fooId",
            "Source":"FromUri",
            "Type":"System.Int32",
            "SubParameters":[

            ]
         }
      ],
      "SupportedHttpMethods":"GET"
   },
   {
      "Name":"Foo",
      "Parameters":[
         {
            "Name":"foo",
            "Source":"FromBody",
            "Type":"ApiTest.Controllers.Foo",
            "SubParameters":[
               {
                  "Name":"fooId",
                  "Source":null,
                  "Type":"System.String",
                  "SubParameters":null
               },
               {
                  "Name":"fooName",
                  "Source":null,
                  "Type":"System.String",
                  "SubParameters":null
               }
            ]
         }
      ],
      "SupportedHttpMethods":"POST"
   }
]

和要求XML为我们提供了:

and asking for XML gives us:

<?xml version="1.0" encoding="UTF-8"?>
<ArrayOfActionMethod xmlns="http://schemas.datacontract.org/2004/07/ApiTest.Controllers" 
                     xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ActionMethod>
        <Name>Bar</Name>
        <Parameters>
            <Parameter>
                <Name>barId</Name>
                <Source>FromUri</Source>
                <SubParameters />
                <Type>System.Int32</Type>
            </Parameter>
        </Parameters>
        <SupportedHttpMethods>GET</SupportedHttpMethods>
    </ActionMethod>
    <ActionMethod>
        <Name>Bar</Name>
        <Parameters>
            <Parameter>
                <Name>bar</Name>
                <Source>FromBody</Source>
                <SubParameters>
                    <Parameter>
                        <Name>barId</Name>
                        <Source i:nil="true" />
                        <SubParameters i:nil="true" />
                        <Type>System.String</Type>
                    </Parameter>
                    <Parameter>
                        <Name>barName</Name>
                        <Source i:nil="true" />
                        <SubParameters i:nil="true" />
                        <Type>System.String</Type>
                    </Parameter>
                </SubParameters>
                <Type>ApiTest.Controllers.Bar</Type>
            </Parameter>
        </Parameters>
        <SupportedHttpMethods>POST</SupportedHttpMethods>
    </ActionMethod>
    <ActionMethod>
        <Name>Foo</Name>
        <Parameters>
            <Parameter>
                <Name>fooId</Name>
                <Source>FromUri</Source>
                <SubParameters />
                <Type>System.Int32</Type>
            </Parameter>
        </Parameters>
        <SupportedHttpMethods>GET</SupportedHttpMethods>
    </ActionMethod>
    <ActionMethod>
        <Name>Foo</Name>
        <Parameters>
            <Parameter>
                <Name>foo</Name>
                <Source>FromBody</Source>
                <SubParameters>
                    <Parameter>
                        <Name>fooId</Name>
                        <Source i:nil="true" />
                        <SubParameters i:nil="true" />
                        <Type>System.String</Type>
                    </Parameter>
                    <Parameter>
                        <Name>fooName</Name>
                        <Source i:nil="true" />
                        <SubParameters i:nil="true" />
                        <Type>System.String</Type>
                    </Parameter>
                </SubParameters>
                <Type>ApiTest.Controllers.Foo</Type>
            </Parameter>
        </Parameters>
        <SupportedHttpMethods>POST</SupportedHttpMethods>
    </ActionMethod>
</ArrayOfActionMethod>

ApiExplorer 类的更多信息可以在<一个找到href=\"http://msdn.microsoft.com/en-us/library/system.web.http.description.apiexplorer%28v=vs.118%29.aspx\">MSDN.

这篇关于列表控制器和类Asp.NET网站的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆