gpt4 book ai didi

.net - Visual Studio for ASP.NET Core 项目中的 "REST API Client"选项?

转载 作者:行者123 更新时间:2023-12-02 02:09:11 34 4
gpt4 key购买 nike

我已经在 Azure 中启动并运行了 ASP.NET REST API。从 Visual 中较旧的 .NET 4.5 项目中,我使用此菜单选项生成了一个客户端:

Old .NET 4.5 project

但是当我创建一个新的 ASP.NET Core (ASP.NET 5) 项目,并且想要生成客户端时,没有这样的选项:

New ASP.NET Core project

在 ASP.NET Core 项目中为我的 REST api 生成客户端的预期方法是什么?

最佳答案

在 ASPNET Core 1.0 上,方法(至少现在,情况可能会改变)是使用 Swagger生成 REST API 文档,完成后,您可以使用 AutoRest自动生成多种语言的客户端。

要在核心应用程序中使用 Swagger,请在 projects.json 文件中添加:

"dependencies": {
...
"Swashbuckle": "6.0.0-rc1-final"
},

然后在 Startup.cs 文件中,您可以添加初始化:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//other uses

//this generates the swagger.json file
app.UseSwaggerGen();

//this is optional, it will generate a visual website for your documentation
app.UseSwaggerUi();
}

UseSwaggerUi 将在 http://yourdomain/swagger/ui/index.html 中生成一个包含“人类可读”内容的 URL。UseSwaggerGen 将在以下位置生成 swagger.json 文件:http://yourdomain/swagger/v1/swagger.json

最后,您需要通过添加以下内容来装饰您的方法,以告诉 Swagger 它们提供哪种输出(输入是自动检测的):

[Produces(typeof(MyItemClass))]
[SwaggerResponse(System.Net.HttpStatusCode.OK, Type = typeof(MyItemClass))]
[HttpGet("{id}")]
public IActionResult Get(string id)
{
if (string.IsNullOrEmpty(id))
{
return HttpBadRequest();
}
var item = _service.GetRecord(id);
if (item == null)
{
return HttpNotFound();
}
return new ObjectResult(item);
}

希望它有助于解决问题。

更新:要生成具有 AutoRest 的客户端,只需转到命令提示符(已安装 AutoRest)并浏览到您的项目文件夹,然后键入:

autorest -Namespace YourDesiredNamespace -Input http://yourapi/swagger/v1/swagger.json

这将在您的项目中创建一个“生成”文件夹,其中包含所有文件和代理类,您甚至可以在 Startup.cs 文件中使用并定义依赖项注入(inject)。

public void ConfigureServices(IServiceCollection services)
{
//....
services.AddSingleton<IYourApi>(provider =>
{
return new YourAPI(new Uri("http://yourapi"));
});
}

关于.net - Visual Studio for ASP.NET Core 项目中的 "REST API Client"选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35864287/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com