【问题标题】:How to provide real time data in Asp Net Mvc that is consuming Asp Net Web Api using HttpClient?如何在使用 HttpClient 使用 Asp Net Web Api 的 Asp Net Mvc 中提供实时数据?
【发布时间】:2017-05-31 21:09:36
【问题描述】:

我正在开发一个使用 Asp Net Web Api 的 Asp Net Mvc 客户端。出于某些原因,我决定使用System.Net.Http.HttpClient 类,而不是jQuery AJAX 来发送数据并从Web api 取回数据。所以我的应用程序流程的概要是这样的——一个mvc控制器,通过使用一些包装HttpClient的服务,从web api获取模型,然后这个模型被传递给View并被显示。我现在面临的问题是如何使用这种方法提供关于我的视图的实时数据?如果我使用AJAX,我可以直接从View 以一定间隔对Web api 服务器进行一些异步调用,而无需重新加载页面来显示更改。我可以使用HttpClient 以某种方式做到这一点吗?如果不是,还有哪些其他替代方案可以与我选择与 web api 通信的方法保持一致? 看看我写的简化代码,以更好地描述我的问题:

这是控制器:

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");
        }
    }
}

这是 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");
            }
        }
    }
}

这是视图:

@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>

现在,如果用户的名字或姓氏发生变化,我希望能够在不重新加载页面的情况下显示它。我有哪些选择?

【问题讨论】:

    标签: asp.net-mvc asynchronous dotnet-httpclient real-time-data


    【解决方案1】:

    现在,如果用户的名字或姓氏发生变化,我希望能够在不重新加载页面的情况下显示它。我有哪些选择?

    您可以在此处完全忽略问题的 WebAPI 部分。此场景与任何其他 MVC 网站相同 - 我如何将数据更改传达给浏览器?

    答案都是一样的:

    • 使用 AJAX。
    • 使用 SignalR。

    您要么必须从浏览器轮询到 MVC 应用程序(即 AJAX),要么必须保持打开的连接并让服务器推送更新(例如 SignalR)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多