在项目根目录下创建一个Configure.json
{
//由它确认使用开发环境还是生产环境 :true表示开发环境 false表示生产环境
"IsTest": false,
//开发环境
"Development": {
"SsoUrl": "locahost:5001/idp/oauth2/authorize",
"SsoClientId": "hc.mvc.test",
"SsoClientSecret": "7b252375d0674f1a84799118227f8888"
},
//生产环境
"Production": {
"SsoUrl": "locahost:5000/idp/oauth2/authorize",
"SsoClientId": "hc.mvc",
"SsoClientSecret": "a6311460a4464c15b5eefa95f6519999"
}
}
再创建一个ConfigHelper.cs类
namespace WebApp
{
public static class ConfigHelper
{
static ConfigHelper()
{
string json = Readjson();
JsonEntity jsonEntity = JsonConvert.DeserializeObject<JsonEntity>(json);
if (jsonEntity != null)
{
//测试环境
if (jsonEntity.IsTest)
{
Models = jsonEntity.Development;
}
//生产环境
else
{
Models = jsonEntity.Production;
}
}
}
/// <summary>
/// json配置文件
/// </summary>
private static string Readjson()
{
//获取配置文件路径
string jsonfile = HttpRuntime.AppDomainAppPath.ToString() + "Configure.json";
using (System.IO.StreamReader file = System.IO.File.OpenText(jsonfile))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o = (JObject)JToken.ReadFrom(reader);
return o.ToString();
}
}
}
public static Variable Models { get; set; }
}
/// <summary>
/// 环境配置
/// </summary>
public class JsonEntity
{
/// <summary>
/// 是否为开发环境:true为开发环境,false为生产环境
/// </summary>
public bool IsTest { get; set; }
/// <summary>
/// 开发环境
/// </summary>
public Variable Development { get; set; }
/// <summary>
/// 生产环境
/// </summary>
public Variable Production { get; set; }
}
/// <summary>
/// 数据实体
/// </summary>
public class Variable
{
/// <summary>
/// BIP统一认证服务器URL地址
/// </summary>
public string SsoUrl { get; set; }
/// <summary>
/// 客户端ID
/// </summary>
public string SsoClientId { get; set; }
/// <summary>
/// 客户端秘钥
/// </summary>
public string SsoClientSecret { get; set; }
}
}
在控制器中使用
public class HomeController : Controller
{
public ActionResult Index()
{
var ssoUrl = ConfigHelper.Models.SsoUrl;
return View();
}
}