从 Global.asax 读取 web.config 文件

问题描述 投票:0回答:2

我的 Web API 项目中有启动代码,该代码尝试从默认情况下发布在 bin 目录内的 web.config 文件中读取值。因为应用程序初始化点是 Global.asax,所以这个级别没有 web.config,所以我需要弄清楚如何在 bin 文件夹中引用它。

这是我的 IIS 目录的根目录:

Root directory of WebAPI project bound in IIS.

每当我尝试使用

ConfigurationManager.AppSettings
从 web.config 文件读取值时,它们都会返回 null。只有当我将 web.config 从 bin 文件夹中移到根目录中时,才会找到这些值。

我尝试添加一些代码,建议在尝试读取值之前将路径强制指向正确的默认位置(bin 文件夹内),但这也不起作用:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Fix web.config location
        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin\\web.config");
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);

        var appId = ConfigurationManager.AppSettings["ApplicationId"];
    }
}

有没有办法强制进入 bin 文件夹内的 web.config 路径?

asp.net-web-api web-config global-asax configurationmanager
2个回答
2
投票

首先,我不明白为什么你将 web.config 文件保存在 bin 文件夹中。 web.config 文件的默认路径始终与 global.asax 相同的文件夹,即应用程序的根目录。我一直在 ASP.NET、ASP.NET WebAPI 和 ASP.NET MVC 应用程序中工作,所有这些应用程序都将 web.config 与 Global.asax 放在同一文件夹中。

如果将 web.config 文件从 bin 目录移动到与 global.asax 相同的目录,您会丢失什么吗?

此外,如果它是您想要读取的连接字符串(正如我从您的上一个问题中得到的),您可以执行以下操作,并将您的connectionSettings放入bin目录的web.config中。

<connectionStrings configSource="bin\connection.config"/>

有关配置文件的更多详细信息,您可以在this文章中找到。


0
投票
public class LogActionFilter : ActionFilterAttribute, IActionFilter
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var request = filterContext.HttpContext.Request;
        
        var configuredName = **ConfigurationManager.AppSettings["CampagneName"]**;
        if (!string.IsNullOrWhiteSpace(configuredName))
        {
            var nameFromURL = request[configuredName];
            if (!string.IsNullOrWhiteSpace(nameFromURL))
            {
                SessionHelper.Add(nameFromURL, configuredName);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.