Send JSON Data From ASP.NET Web API To Splunk

Introduction

This is what we are going to see in this article:
 
 

SPLUNK

Splunk (the product) captures, indexes and correlates real-time data in a searchable repository from which it can generate graphs, reports, alerts, dashboards and visualizations. It is mainly used for Web Analytics.

Here what I am going to do,

Creating the Web API service which is used to get the feedback from the users/consumer and store it in DB this is usual but now we are going to take a next step by sending the data to splunk enterprise which enables you to search, monitor and analyze any machine data for powerful new insights

The article flow as follows,

  1. Installing Splunk Enterprise
  2. Creating a REST API using ASP.NET WEB API
  3. Splunk in picture - HTTP Event Collector
  4. Generating a HTTP Event Collector Token
  5. Sending a data from ASP.NET WEB API to Splunk
  6. Generating the Dashboard in Splunk 

1.Install the Splunk

Download the Splunk Enterprise v6.4.

First it will compute the disk space and the installation process takes place as show in figure,

   

After successful installation, the First time signing page will open in browser,

 
 
Use Username:admin and password: changeme,

Change your password as required, 



2. Creating a WEB API

Create a Web API application using an installed web template in Visual Studio as in the following figures,

  
 
   

Creating a Model Classes:

In the Solution Explorer, right click the model folder, Add-> Class and name it as Feedback

Feedback.cs

  1. public class Feedback  
  2.   {  
  3.         
  4.       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  5.       public int FeedbackID { getset; }  
  6.       public string Message { getset; }  
  7.   }  

Install the Entity Framework

We are using the Entity framework for data access, Install the Enityframework using nuget packager as shown in following figure,

  

Creating a Context Class:

Add one more class in the Model and name it FeedbackContext which is our Entity framework code first context.

FeedbackContext.cs

  1. public class FeedbackContext: DbContext  
  2.  {  
  3.      public FeedbackContext() : base("name=DefaultConnection")    
  4.      {  
  5.      }  
  6.   
  7.      public System.Data.Entity.DbSet<Splunk_WEBAPI.Models.Feedback> Feedbacks { getset; }  
  8.  }  

Connection String in Web.comfig file

  1. <connectionStrings>    
  2.     <add name="DefaultConnection" connectionString="Data Source= server name;Initial Catalog= db_name;Integrated Security=True"    
  3.   </connectionStrings>    
Seed the Database:

Now, open the Package manager console and run the following commands,

  1. Enable-migrations: This will add the folder called migration with code file named configuration.cs.
  2. Add-Migration Initial: Check your Web config file and ensure the SQL connection string, 

    Open configuration.cs file under migration folder and add the following code in seed method,

Configuration.cs

  1. protected override void Seed(Splunk_WEBAPI.Models.FeedbackContext context)    
  2.        {    
  3.             context.Feedbacks.AddOrUpdate(new Models.Feedback { Message = "Test" });    
  4. }    
3. Update-Database

This will run the seed method,

Check you database which is created

  

Feedback Table

 

From the API service you can notice that the user post the feedback and it is going to store in the DB, so now we need to perform analytics on the data send by users with the help of splunk enterprise.

3. SPLUNK IN PICTURE

HTTP EVENT Collector:

The Event Collector is a new way to send data to Splunk Enterprise. Notably, the EC enables you to send data over HTTP (or HTTPS) directly to Splunk Enterprise from your application.

The basics of Splunk HTTP Event Collector are relatively simple,

  1. Turn on the Event Collector in Splunk Enterprise by enabling the HTTP input endpoint. It is not enabled by default.
  2. From the Splunk Enterprise instance, generate an EC token.
  3. On the machine that will log to Splunk Enterprise, create a POST request, and set its authentication header to include the EC token.
  4. POST data in JSON format to the EC token receiver. 

4. Jump into Splunk

 Generating a Token

The token for http event collector can be created in following step,

1. Select Settings->Data Inputs
 

2. click on HttpEventCollector in data input page,
 
  
 
Now, it's time to create a HTTPEventCollector Tokens, click on new token in HTTP event collector page,
 
 
 

Give the Token Name and click next, 

  

Select the main in available items and click next,

  
 

Review the token settings,


Click on global setting on HTTPEventCollector page, to get the HTTP setting and make sure that all the tokens are enabled,
 
  
 
5. Sending a data from ASP.NET WEB API to Splunk  

Now open the ASP.NET WEB API project which we have created and replace the code in Feedbackcontroller.cs by following code and download the trace listener and SLAB libraries from nuget packager as shown in following figures,



FeedbackController.cs
  1. FeedbackContext db = new FeedbackContext();  
  2.         [HttpPost]  
  3.         [Route("Message")]  
  4.         [ResponseType(typeof(Feedback))]  
  5.         public async Task<IHttpActionResult> SaveFeedback(Feedback feedback)  
  6.         {  
  7.             if (!ModelState.IsValid)  
  8.             {  
  9.                 return BadRequest(ModelState);  
  10.             }  
  11.   
  12.             db.Feedbacks.Add(feedback);  
  13.             await db.SaveChangesAsync();  
  14.               
  15.   
  16.   
  17.             ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>  
  18.             {  
  19.                 return true;  
  20.             };  
  21.   
  22.             var middleware = new HttpEventCollectorResendMiddleware(100);  
  23.             var ecSender = new HttpEventCollectorSender(new Uri("https://localhost:8088"),  //http port as set in global setting
  24.                 "9201EA75-D7DD-40CD-8D1A-6714F66E4E29",  // token
  25.                 null,  
  26.                 HttpEventCollectorSender.SendMode.Sequential,  
  27.                 0,  
  28.                 0,  
  29.                 0,  
  30.                 middleware.Plugin  
  31.             );  
  32.             ecSender.OnError += o => Console.WriteLine(o.Message);  
  33.             ecSender.Send(Guid.NewGuid().ToString(), "INFO"nullnew { Foo = feedback.Message });  
  34.             await ecSender.FlushAsync();  
  35.   
  36.             return Ok("Thanks for your feedback");  
  37.               
  38.         }  
  39.     }  

Creating a HTML page

Create a new HTML page in the project.

Design:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  7.     <script src="scripts/jquery-1.9.1.js"></script>  
  8.     <script src="scripts/Feedback.js"></script>  
  9. </head>  
  10. <body>  
  11.     <form>  
  12.           
  13.         <div class="container">  
  14.             <h3 style="font-style:italic">Feedback</h3>  
  15.             <br />  
  16.             <div class="row">  
  17.                 <div class="form-group">  
  18.               <label>Message:</label>    
  19.                 <textarea id="TxtFeddback" ></textarea>  
  20.                     </div>  
  21.             </div>  
  22.             <br />  
  23.               
  24.             <button id="btn_feedback" class="btn btn-default">Submit</button>  
  25.             <br />  
  26.             <br />  
  27.             <div id="responediv" class="row" style="color:green">  
  28.   
  29.             </div>  
  30.         </div>  
  31.     </form>  
  32. </body>  
  33. </html>  
JavaScript:
  1. $(document).ready(function()  
  2. {  
  3.     $("#btn_feedback").click(function (e) {  
  4.         e.preventDefault();  
  5.        
  6.         $.ajax({  
  7.             url: "api/Feedback/Message",  
  8.             type: "POST",  
  9.             data: { Message: $("#TxtFeddback").val() },  
  10.             success: function (data) {  
  11.                 $("#TxtFeddback").val('')  
  12.                 $("#responediv").html(data);  
  13.             }  
  14.         })  
  15.     })  
  16.    
  17. })  
Demo:
 
  
Data in Table:
 
   

Event created in splunk:

 

Hurray! The data are collected as events in the Splunk.

6.Creating a Dashboard

Click on save as and select dashboard panel in the search, the wizard will be open to create a dashboard,



Click save after giving the dashboard name, then select dashboard from the search page to open the dashboard page as shown in below figure,

 
 


Click on Feedback Dashboard to view the events,


Conclusion

From this article we have learned how to transport the data from ASP.NET Web API to Splunk using HTTPEvent Collector. I hope you have enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcomed.

Read more articles on ASP.NET: