Get Response Message From Config File In .NET Core Web API

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.

 Get Response Message From Config File In .NET Core Web API

Create a model for API response message having "Code" and "Message" as properties.

  1. namespace ResponseMessageFromConfig  
  2. {  
  3.     public class ApiResponse  
  4.     {  
  5.         public int Code { getset; }  
  6.         public string Message { getset; }  
  7.     }  
  8. }  

Create a responsemessage.json file where we will keep all possible messages which we are going to return as an API response.

responsemessage.json

  1. {  
  2.   "ResponseMessage": {  
  3.     "Values": {  
  4.       "Success""Successful!",  
  5.       "NoData""No Record Found!"  
  6.     }  
  7.   }  
  8. }  

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.

  1. using System.Collections.Generic;  
  2.   
  3. namespace ResponseMessageFromConfig  
  4. {  
  5.     public class ResponseMessage  
  6.     {  
  7.         public Dictionary<stringstring> Values  
  8.         {  
  9.             get;  
  10.             set;  
  11.         }  
  12.     }  
  13. }  

Create a message enum which will be used to pass as key and get the message from config.

  1. namespace ResponseMessageFromConfig  
  2. {  
  3.     public class Constant  
  4.     {  
  5.     }  
  6.   
  7.     public enum Message  
  8.     {  
  9.         Success = 200,  
  10.         NoData = 204  
  11.     }  
  12. }  

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.

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5.   
  6. namespace ResponseMessageFromConfig  
  7. {  
  8.     public class Startup  
  9.     {  
  10.         public Startup(IConfiguration configuration, IHostingEnvironment env)  
  11.         {  
  12.             var builder = new ConfigurationBuilder()  
  13.                 .SetBasePath(env.ContentRootPath)  
  14.                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  15.                 .AddJsonFile($"Config/responsemessage.json", optional: false, reloadOnChange: true)  
  16.                 .AddEnvironmentVariables();  
  17.             configuration = builder.Build();  
  18.   
  19.   
  20.             Configuration = configuration;  
  21.         }  
  22.   
  23.         public IConfiguration Configuration { get; }  
  24.   
  25.         public void ConfigureServices(IServiceCollection services)  
  26.         {  
  27.             services.AddSingleton(Configuration.GetSection("ResponseMessage").Get<ResponseMessage>());  
  28.             services.Configure<ResponseMessage>((setting) =>  
  29.             {  
  30.                 Configuration.GetSection("ResponseMessage").Bind(setting);  
  31.             });  
  32.   
  33.             services.AddMvc();  
  34.         }  
  35.   
  36.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  37.         {  
  38.             if (env.IsDevelopment())  
  39.             {  
  40.                 app.UseDeveloperExceptionPage();  
  41.             }  
  42.   
  43.             app.UseMvc();  
  44.         }  
  45.     }  
  46. }  

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.

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.Extensions.Options;  
  3. using System.Collections.Generic;  
  4.   
  5. namespace ResponseMessageFromConfig.Controllers  
  6. {  
  7.     [Route("api/[controller]")]  
  8.     public class ValuesController : Controller  
  9.     {  
  10.         private readonly ResponseMessage responseMessage;  
  11.         public ValuesController(IOptionsSnapshot<ResponseMessage> responseMessage)  
  12.         {  
  13.             this.responseMessage = responseMessage.Value;  
  14.         }  
  15.   
  16.         // GET api/values  
  17.         [HttpGet]  
  18.         public IEnumerable<string> Get()  
  19.         {  
  20.             ApiResponse apiResponse = new ApiResponse();  
  21.             apiResponse.Code = (int)Message.Success;  
  22.             apiResponse.Message = responseMessage.Values[Message.Success.ToString()];  
  23.   
  24.             return new string[] { apiResponse.Code.ToString(), apiResponse.Message };  
  25.         }  
  26.   
  27.         // GET api/values/5  
  28.         [HttpGet("{id}")]  
  29.         public string Get(int id)  
  30.         {  
  31.             return "value";  
  32.         }  
  33.   
  34.         // POST api/values  
  35.         [HttpPost]  
  36.         public void Post([FromBody]string value)  
  37.         {  
  38.         }  
  39.   
  40.         // PUT api/values/5  
  41.         [HttpPut("{id}")]  
  42.         public void Put(int id, [FromBody]string value)  
  43.         {  
  44.         }  
  45.   
  46.         // DELETE api/values/5  
  47.         [HttpDelete("{id}")]  
  48.         public void Delete(int id)  
  49.         {  
  50.         }  
  51.     }  
  52. }  

Run the application and you can see a response message as ‘Successful!’

Get Response Message From Config File In .NET Core Web API 

Now, for testing our reloadOnChange feature, let’s modify our message from ‘Successful!’ to ‘Successful.’. We removed the exclamation (!) and added the dot (.).

Get Response Message From Config File In .NET Core Web API 

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.

Get Response Message From Config File In .NET Core Web API 

You can download the sample from here.


Similar Articles