You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 F# Web API如何读取Appsettings.Json中的连接字符串

在F# .NET 6 Web API中读取appsettings.json的连接字符串

F# .NET 6 Web API同样支持通过依赖注入IConfiguration读取配置,逻辑和C#一致,只是语法有所区别,以下是具体实现:

1. 控制器中读取示例

和C#的构造函数注入逻辑一致,在F#类型的构造函数中接收IConfiguration实例,即可调用GetConnectionString方法读取配置:

open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Configuration

[<ApiController>]
[<Route("api/[controller]")>]
type TestController(configuration: IConfiguration) =
    inherit ControllerBase()

    [<HttpGet("connect")>]
    member this.Connect() =
        // 读取指定名称的连接字符串
        let connectionString = configuration.GetConnectionString("myConnectionString")
        
        // 此处添加业务逻辑,比如初始化数据库连接等操作
        Ok($"获取到的连接字符串:{connectionString}")

2. 自定义服务中读取示例

如果需要在自定义服务类中读取配置,同样通过构造函数注入IConfiguration:

open Microsoft.Extensions.Configuration

type TestService(configuration: IConfiguration) =
    /// 获取数据库连接字符串
    member this.GetDbConnectionString() =
        configuration.GetConnectionString("myConnectionString")

注意事项

  • .NET 6 Web API模板默认已自动加载appsettings.json,无需额外配置加载逻辑
  • GetConnectionString是IConfiguration的扩展方法,必须确保打开Microsoft.Extensions.Configuration命名空间

内容的提问来源于stack exchange,提问作者arborinfelix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:35:27