问题描述
在我的 C# 项目中有 APIKeys.cs 文件,其中包含带有 API 密钥的常量字符串.我希望这些字符串在 Git 服务器中为空,但在我的本地计算机中有实际的 API 密钥.所以拉项目的人可以毫无问题地编译它,而且我的本地计算机仍然会在同一个文件中拥有 API 密钥.
In my C# project have APIKeys.cs file which have const strings with API keys.I want those strings to be empty in Git server but have actual API keys in my local computer.So peoples who pull project can compile it without problem and still my local computer gonna have API keys in same file.
如果我尝试上传带有空字符串的 APIKeys.cs 文件,那么我无法拥有带有 API 密钥的本地文件,因为当我尝试推送它时,它会覆盖空的 APIKeys.cs 文件.我也不能忽略这个文件,因为它会从 Git 服务器中删除空的 APIKeys.cs 文件.
If I try to upload APIKeys.cs file with empty strings then I can't have local file with API keys because when I try to push it, it will overwrite empty APIKeys.cs file. Also I can't ignore this file too because it will remove empty APIKeys.cs file from Git server.
那么对于这个问题,什么是最好的自动化方法,它允许服务器中的类文件带有空字符串,这样当人们提取它并在本地计算机中有真实的类文件时,项目将是可编译的?
So what is best automated approach for this problem which will allow class file with empty strings in server, so project will be compileable when people pull it and have real class file in local computer?
推荐答案
我现在想出了另一个解决方案,虽然不完美但对我来说仍然足够好,例如:
I figured another solution now which is not perfect but still good enough for me, example:
APIKeys.cs
文件:
public static partial class APIKeys
{
public static readonly string ImgurClientID = "";
public static readonly string ImgurClientSecret = "";
public static readonly string GoogleClientID = "";
public static readonly string GoogleClientSecret = "";
public static readonly string PastebinKey = "";
...
}
APIKeysLocal.cs
文件:
public static partial class APIKeys
{
static APIKeys()
{
ImgurClientID = "1234567890";
ImgurClientSecret = "1234567890";
GoogleClientID = "1234567890";
GoogleClientSecret = "1234567890";
PastebinKey = "1234567890";
...
}
}
忽略 Git 中的 APIKeysLocal.cs
文件,如果没有这个文件的人从解决方案资源管理器中删除这个文件,他们仍然可以编译项目.
Ignore APIKeysLocal.cs
file in Git and people who don't have this file can still be able to compile project if they remove this file from solution explorer.
我还会使用项目预构建事件自动创建空的 APIKeysLocal.cs
文件:
I also automatically create empty APIKeysLocal.cs
file if it is not already exists using project pre build event:
cd $(ProjectDir)APIKeys\
if not exist APIKeysLocal.cs (
type nul > APIKeysLocal.cs
)
这样用户不需要做任何事情就可以编译项目.
That way user don't need to do anything to be able to compile project.
这篇关于在 Git 中隐藏 API 密钥的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!