0

I am developing an Asp Net Mvc client that is consuming Asp Net Web Api. For some reasons I decided to use System.Net.Http.HttpClient class, instead of jQuery AJAX to send data and get it back from the web api. So the outline of my application flow is this - an mvc controller, by using some service that wraps HttpClient within, gets the model from the web api, and then this model is passed to a View and gets displayed. The problem I am facing now is how can I provide real time data on my views using this approach? If I was using AJAX, I could make some asynchronous calls with some intervals to the web api server directly from a View and without reloading the page display the changes. Can I do it somehow using HttpClient? If not, what are some other alternatives that will align with the approach I chose to communicate with the web api? Take a look at the simplified code I wrote to better describe my issue:

This is the controller:

public class UsersController : Controller
{
    private readonly IUserHttpService _userHttpService;

    public UsersController(IUserHttpService userHttpService)
    {
        _userHttpService = userHttpService;
    }

    public async Task<ActionResult> Index(int userId)
    {
        try
        {
            User user = await _userHttpService.GetUserById(userId);
            return View(user);
        }
        //some simplified exception handling 
        catch (Exception)
        {
            return View("UnexpectedError");
        }
    }
}

This is UserHttpService:

public class UserHttpService : IUserHttpService
{
    private const string _baseUri = "http://localhost/rs-webapi/api/users/";

    public async Task<User> GetUserById(int userId)
    {
        string requestUri = $"{_baseUri}getuserbyid?userId={userId}";

        //Here using HttpClient I fetch the data from web api 
        //(and I know that it's better to have one HttpClient for the whole app, 
        //it's just for the sake of simplicity)
        using (HttpClient httpClient = new HttpClient())
        {
            HttpResponseMessage response = await httpClient.GetAsync(requestUri);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsAsync<User>();
            }
            else
            {
                throw new System.Exception("Something went wrong");
            }
        }
    }
}

And this is the View:

@model Entities.Entities.UserBase
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>First name: @Model.FirstName, Last name: @Model.LastName</p>
</body>
</html>

Now if the user first name or last name changes, I would like to be able to display it without reloading the page. What are my options?

Mykhailo Seniutovych
  • 3,527
  • 4
  • 28
  • 50

1 Answers1

0

Now if the user first name or last name changes, I would like to be able to display it without reloading the page. What are my options?

You can completely ignore the WebAPI part of your question here. This scenario is the same as any other MVC website - how do I communicate changes in data to the browser?

And the answers are the same:

  • Use AJAX.
  • Use SignalR.

You either have to poll from your browser to your MVC app (i.e., AJAX), or you have to keep an open connection and have the server push updates (e.g., SignalR).

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810