SignalR

SignalR is a library for ASP NET developers to add real-time web functionality to applications. Real-time web functionality is the ability to have server-side code push content to the connected clients as it happens, in real-time.Most developer use ASP Net WebAPI and SignalR for there real time update

ASP.Net WebAPI and SignalR
ASP Net WebAPI and SignalR

Unlocking Real-Time Potential with ASP NET WebAPI

ASP NET WebAPI, a framework designed for building HTTP services, has become a cornerstone in modern web development. Its ability to streamline the creation of RESTful APIs has revolutionized the way data is exchanged between clients and servers. By embracing a straightforward architecture, developers can effortlessly expose their application’s data and functionalities.

Revitalizing Communication Channels with SignalR Integration

SignalR, on the other hand, introduces a layer of real-time functionality to ASP NET applications, enabling seamless bi-directional communication between the server and connected clients. This open-source library simplifies the complexities of handling websockets, long polling, and other real-time communication protocols, making it an ideal companion for enhancing user engagement.

Unveiling the Symbiosis: ASP NET WebAPI and SignalR

1. Streamlined Data Delivery with WebAPI: ASP NET WebAPI excels in delivering data in a concise and structured manner. By embracing RESTful principles, it ensures efficient communication between clients and servers. Developers can harness its capabilities to transmit updates and changes seamlessly, laying the foundation for real-time interactions.

2. Dynamic WebSocket Integration: SignalR seamlessly integrates with ASP NET WebAPI, providing a robust solution for implementing websockets. This dynamic duo facilitates low-latency communication, ensuring that data updates are instantly propagated to connected clients. This real-time synchronization contributes to a responsive and immersive user experience.

3. Building Responsive Interfaces: Leveraging SignalR’s real-time capabilities, developers can create responsive user interfaces that react promptly to changing data. Whether it’s live notifications, collaborative editing, or interactive dashboards, the integration with ASP NET WebAPI allows for the creation of applications that transcend traditional request-response architectures.

Crafting a Real-Time ASP NET WebAPI and SignalR Application

1. Setting Up the Foundation: Begin by establishing the groundwork for your application, setting up ASP NET WebAPI to expose the desired endpoints. Define the data structure and operations that will be the backbone of your real-time features.

2. Integrating SignalR into the Mix: Seamlessly integrate SignalR into your ASP NET WebAPI project to unlock real-time communication capabilities. Leverage SignalR hubs to manage connections and broadcast updates to clients, creating a responsive and engaging user experience.

3. Implementing Real-Time Features: With the foundation in place, start implementing real-time features using SignalR. Whether it’s live chat, notifications, or collaborative editing, the integration with ASP NET WebAPI ensures that your application stays synchronized and responsive.

Get it on NuGet

Install-Package Microsoft.AspNet.SignalR Following article explain when user update the record how to user SignalR and refresh the page

Web API

[HttpGet] 

[Route("getOrderDetails/{OrderStatus?}")]
 public IEnumerable<Orders> GetOrderDetails()
 {
      var _orderDetails= _repo.GetOrderDetails();
      return _orderDetails;
 }

 [HttpPut]

 [Route("updateOrderStatus")]

 public IHttpActionResult UpdateOrderStatus([FromBody] Orders Order)
 {
      var response = new ResponseMassege();
      response = _repo.UpdateOrderStatus(Order);
  
      if (response.ResponseMessage != "Successful")
                 return BadRequest();
      else
          return Ok(response);
 } 

Index Page

  <div class="row" id="divOrder">
     @foreach (var order in Model)
     {
         <div class="col-md-4">
             <div class="col-xs-6 bg-primary">@order.OrderType</div><div class="col-xs-6 bg- 
                   primary">@order.OrderDate</div><br />
             <div class="col-xs-6 bg-success">@order.OrderRefNo</div><div class="col-xs-6 bg-
                  success">@order.OrderThroughDescription</div>
             <div>
                 @{Html.RenderAction("OrderItemDetails", new { OrderRefNo = order.OrderRefNo });}
             </div>
             <br />
             <div><button type="button" class="btn btn-primary" 
                         onclick="UpdatePreparingOrderStatus('@order.OrderRefNo');">Update</button></div>
         </div>
     }
 </div> 

JavaScript

 $(function () {
         var order = $.connection.ordersHub;
         order.client.GetOrderDetails = function () {
             GetOrderDetails();
         };
         $.connection.hub.start();
     });
  
     function GetOrderDetails() {
         $.ajax({
             type: "POST",
             url: '@Url.Action("Index", "Orders")',
             data: {},
             beforeSend: function () {
  
             }, success: function (data) {
                 $("#divOrder").html(data);
             },
             error: function (xhr, errorType, exception) {
                 var errorMessage = exception || xhr.statusText;
             }
         });
     } 

Controller

 public async Task<ActionResult> Index()
         {
             List<Orders> orders = new List<Orders>();
             using (var client = new HttpClient())
             {
                 string requestParams = string.Empty;
  
                 List<KeyValuePair<string, string>> iputParams = new List<KeyValuePair<string, string>>();
                 iputParams.Add(new KeyValuePair<string, string>("OrderStatus", OrderStatus)); 
  
                 requestParams = new FormUrlEncodedContent(iputParams).ReadAsStringAsync().Result;
  
                 client.BaseAddress = new Uri(Baseurl);
                 client.DefaultRequestHeaders.Clear();
                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                 HttpResponseMessage Res = await client.GetAsync("api/Orders/getOrderDetails?" + requestParams);
                 if (Res.IsSuccessStatusCode)
                 {
                     var ResponseMessage= Res.Content.ReadAsStringAsync().Result;
                     orders = JsonConvert.DeserializeObject<List<Orders>>(ResponseMessage);
                 }
                 return View(orders);
             }
         }
 public async Task<ResponseMassege> UpdatePreparingOrderStatus(string OrderRefNo)
         {
             ResponseMassege responseMassege = new ResponseMassege();
             using (var client = new HttpClient())
             { 
                 client.BaseAddress = new Uri(Baseurl);
                 client.DefaultRequestHeaders.Clear();
  
                 var orderToSend = new Orders()
                 {
                     OrderRefNo = OrderRefNo,
                     OrderStatus = OrderStatus.Preparing
                 };
  
                 var orderContent = new StringContent(JsonConvert.SerializeObject(orderToSend), Encoding.UTF8, 
                                              "application/json");
  
                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                 HttpResponseMessage Res = await client.PutAsync("api/Orders/UpdateOrderStatus", orderContent);
                 if (Res.IsSuccessStatusCode)
                 {
                     var ResponseMessage = Res.Content.ReadAsStringAsync().Result;
                     responseMassege = JsonConvert.DeserializeObject<ResponseMassege>(ResponseMessage);
                 }
                 OrdersHub.GetOrderDetails();
                 return responseMassege;
             }
         } 

Hub Class

  public class OrdersHub:Hub
 {
         [HubMethodName("getOrderDetails")]
         public static void GetOrderDetails()
         {
              IHubContext context = 
                    GlobalHost.ConnectionManager.GetHubContext<OrdersHub>();
              context.Clients.All.GetOrderDetails();
         }
 } 
ASP Net WebAPI and SignalR: Easy way Learn