问题描述
我已经将服务器端存储过程命名为sample(这是默认存储过程),如何在.net Web API中调用它?
I've made server side stored procedure named sample ( it's the default stored procedure) how can I call it inside my .net web API ?
推荐答案
使用 V3 .NET SDK ,您可以像这样执行存储过程:
Using the V3 .NET SDK, you can execute your stored procedure like so:
CosmosClient client = new CosmosClient("connection string");
Container container = client.GetContainer("YourDbName", "YourContainerName");
StoredProcedureExecuteResponse response = await container.Scripts.ExecuteStoredProcedureAsync(
"sample", // your stored procedure name
new PartitionKey("Partition Key you want to run it on"),
new dynamic[] { "Your First parameter", "Your second parameter" });
// If your stored procedure returns some information, you can use the Type of the data you expect. For example, if you expect a string
StoredProcedureExecuteResponse<string> responseWithData = await container.Scripts.ExecuteStoredProcedureAsync<string>(
"sample", // your stored procedure name
new PartitionKey("Partition Key you want to run it on"),
new dynamic[] { "Your First parameter", "Your second parameter" });
如果要创建Web API,请确保维护 Singleton实例,通常将其注册为Startup的一部分.不要为每个操作创建CosmosClient的新实例.
If you are creating a Web API, please make sure you maintain a Singleton instance of the CosmosClient, often registering it as part of the Startup. Do not create new instances of the CosmosClient for each operation.
这意味着,在
This means that, in your Startup.cs
where services are being registered in the DI container, you can add it there:
public void ConfigureServices(IServiceCollection services)
{
// ... other code you might already have
CosmosClient client = new CosmosClient("connection string");
services.AddSingleton(client);
}
并在控制器中注入CosmosClient
实例:
And inject the CosmosClient
instance in your Controller:
public class MyController
{
private readonly CosmosClient cosmosClient;
public MyController(CosmosClient cosmosClient)
{
this.cosmosClient = cosmosClient;
}
public async Task<IActionResult> MyMethod()
{
// execute the stored procedure or use this.cosmosClient
}
}
完整的Web API示例: https://github.com/Azure-Samples/cosmos-dotnet-core-todo-app
Full Web API sample: https://github.com/Azure-Samples/cosmos-dotnet-core-todo-app
这篇关于在我的CosmosDb中创建存储过程,如何通过我的.net wep API(连接到我的cosmosDb)访问它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!