WebAPI控制器方法未显示在swagger中

本文关键字:swagger 显示 控制器 方法 WebAPI | 更新日期: 2023-09-27 17:57:34

C#Azure Web Service API

我创建了一个web服务,我正在使用一个移动应用程序连接它。我在控制器容器中创建了默认的CRUD控制器,所有这些方法都显示得很好。

我在控制器中添加了一个新方法来执行CRUD中未涵盖的任务,并且它不会以招摇的方式显示。示例:

    public async Task<IHttpActionResult> test(tblProfileList test)
    {
        // just testing to see if this method shows in swagger
        tblProfileList ProfileList = await db.tblProfileLists.FindAsync("10");
        return NotFound(); // yes, 10 will never be found but that's not the point of this test
    }

即使我修改了控制器中现有的CRUD方法,它最终也会将其从swagger中删除。这似乎是某种映射问题,但除了在WebApiConfig.cs:中之外,我看不出这些方法在哪里注册

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

为什么我不能更改方法的名称或在现有控制器中添加新方法?或者我应该说,我如何才能在中添加一个方法,并让它大摇大摆地展示出来?

WebAPI控制器方法未显示在swagger中

将[Route]属性添加到方法中。还要确保您的控制器名称实际上以…..作为后缀。。。。。控制器。

谁调用您的公共静态void Register(HttpConfiguration config)函数?

据我所知,您需要创建Global.asax文件添加后,您将得到如下文件:

public class Global
{
    protected void Application_Start(object sender, EventArgs e)
    {
    }
    protected void Session_Start(object sender, EventArgs e)
    {
    }
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
    }
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
    }
    protected void Application_Error(object sender, EventArgs e)
    {
    }
    protected void Session_End(object sender, EventArgs e)
    {
    }
    protected void Application_End(object sender, EventArgs e)
    {
    }
}

只需在Application_Start函数上添加这一行,那么Register函数实际上将被称为

protected void Application_Start(object sender, EventArgs e)
{
    GlobalConfiguration.Configure(YouClassName.Register);
}

将方法名称更改为GetTest():

  public async Task<IHttpActionResult> GetTest(tblProfileList test)
    {
        // just testing to see if this method shows in swagger
        tblProfileList ProfileList = await db.tblProfileLists.FindAsync("10");
        return NotFound(); // yes, 10 will never be found but that's not the point of this test
    }