如何从根URL重定向到/ swagger/ui/index?

v.k*_*chy 13 c# asp.net-web-api swagger swashbuckle

我有一个安装了Swashbuckle的WebApi项目.

在默认设置中,我必须在浏览器中打开http://localhost:56131/swagger/ui/index以查看我的操作说明和测试页面.我希望它可以从站点的根目录访问:http://localhost:56131/.我怎样才能做到这一点?

v.k*_*chy 27

受此类问题的答案影响,略有修改的代码:

public class WebApiConfig
{
    public static void Configure(IAppBuilder app)
    {
        var httpConfig = new HttpConfiguration();

        // Attribute routing
        config.MapHttpAttributeRoutes();

        // Redirect root to Swagger UI
        config.Routes.MapHttpRoute(
            name: "Swagger UI",
            routeTemplate: "",
            defaults: null,
            constraints: null,
            handler: new RedirectHandler(SwaggerDocsConfig.DefaultRootUrlResolver, "swagger/ui/index"));

        // Configure OWIN with this WebApi HttpConfiguration
        app.UseWebApi(httpConfig);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样就没有必要像@bsoulier那样创建新的WebAPI控制器.

此解决方案基于已存在RedirectHandler的Swashbuckle.Core程序集类.


Ben*_*ier 10

如果您确定使用Web API项目,则可以:

[Route(""), HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public HttpResponseMessage RedirectToSwaggerUi()
{
    var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Found);
    httpResponseMessage.Headers.Location = new Uri("/swagger/ui/index", UriKind.Relative);
    return httpResponseMessage;
}
Run Code Online (Sandbox Code Playgroud)

请注意ApiExplorerSettings属性的使用,以便它不会显示在Swagger定义中.


Gun*_*éus 10

上述答案的更简单的变体:

public class DefaultController : Controller
{
    [Route(""), HttpGet]
    [ApiExplorerSettings(IgnoreApi = true)]
    public RedirectResult RedirectToSwaggerUi()
    {
        return Redirect("/swagger/");
    }
}
Run Code Online (Sandbox Code Playgroud)

越简单越好!这对我有用。