Assume that you are working on an enterprise level application and exposing a huge number of APIs to different clients. Now, from the API, you are returning some custom message and post-deployment, you need to change that custom message. If you don’t load it from config, then you have to modify the code and redeploy your project.
So, as a part of the solution, we will get the messages from the config file and load the config in such a way that whenever you change it, it will be reloaded automatically. Let’s see the step by step implementation of the same.
Open Visual Studio and create a new project. Select API as the template and click the OK button.
Create a model for API response message having "Code" and "Message" as properties.
- namespace ResponseMessageFromConfig
- {
- public class ApiResponse
- {
- public int Code { get; set; }
- public string Message { get; set; }
- }
- }
Create a responsemessage.json file where we will keep all possible messages which we are going to return as an API response.
responsemessage.json
- {
- "ResponseMessage": {
- "Values": {
- "Success": "Successful!",
- "NoData": "No Record Found!"
- }
- }
- }
Create a class which will match with our config. As we may have n number of key-value pairs in our config, we will take Dictionary to store the same.
- using System.Collections.Generic;
-
- namespace ResponseMessageFromConfig
- {
- public class ResponseMessage
- {
- public Dictionary<string, string> Values
- {
- get;
- set;
- }
- }
- }
Create a message enum which will be used to pass as key and get the message from config.
- namespace ResponseMessageFromConfig
- {
- public class Constant
- {
- }
-
- public enum Message
- {
- Success = 200,
- NoData = 204
- }
- }
Add the JSON file in the startup class constructor and make sure that the value of "optional" should be false and reloadOnChange should be true. This means whenever you change your config, it will reload your config.
Add the ResponseMessage class in the service collection so that it will be injected whenever we need it. Also, get the data from config and bind it with that class dictionary.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace ResponseMessageFromConfig
- {
- public class Startup
- {
- public Startup(IConfiguration configuration, IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"Config/responsemessage.json", optional: false, reloadOnChange: true)
- .AddEnvironmentVariables();
- configuration = builder.Build();
-
-
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddSingleton(Configuration.GetSection("ResponseMessage").Get<ResponseMessage>());
- services.Configure<ResponseMessage>((setting) =>
- {
- Configuration.GetSection("ResponseMessage").Bind(setting);
- });
-
- services.AddMvc();
- }
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseMvc();
- }
- }
- }
Inject ResponseMessage in the ValuesController via constructor. Here, we are using IOptionsSnapshot which is used to access the value of our ResponseMessage for the lifetime of a request.
In the GET method, get the message from ResponseMessage instance by passing the enum value as parameter.
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System.Collections.Generic;
-
- namespace ResponseMessageFromConfig.Controllers
- {
- [Route("api/[controller]")]
- public class ValuesController : Controller
- {
- private readonly ResponseMessage responseMessage;
- public ValuesController(IOptionsSnapshot<ResponseMessage> responseMessage)
- {
- this.responseMessage = responseMessage.Value;
- }
-
-
- [HttpGet]
- public IEnumerable<string> Get()
- {
- ApiResponse apiResponse = new ApiResponse();
- apiResponse.Code = (int)Message.Success;
- apiResponse.Message = responseMessage.Values[Message.Success.ToString()];
-
- return new string[] { apiResponse.Code.ToString(), apiResponse.Message };
- }
-
-
- [HttpGet("{id}")]
- public string Get(int id)
- {
- return "value";
- }
-
-
- [HttpPost]
- public void Post([FromBody]string value)
- {
- }
-
-
- [HttpPut("{id}")]
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- [HttpDelete("{id}")]
- public void Delete(int id)
- {
- }
- }
- }
Run the application and you can see a response message as ‘Successful!’
Now, for testing our reloadOnChange feature, let’s modify our message from ‘Successful!’ to ‘Successful.’. We removed the exclamation (!) and added the dot (.).
Refresh the browser and you can see the message as ‘Sucessful.’ i.e. the updated one. So here, we haven’t recompiled or redeployed but still, we get the updated message on the change of the config file.
You can download the sample from here.