首页 > 解决方案 > 使用 Post 方法将数据传递到 SignalR Hub 到 Web Api 返回:远程服务器返回错误:(404)未找到

问题描述

最近,我刚开始学习 SignalR,并且一直在测试我在 GitHub 上找到的一个项目。但是,我在尝试将数据发布到 Web api 部分时确实卡住了。

我只是完成了所有工作,但我无法真正让这个项目以某种方式工作。这基本上是该项目的程序。它是一个控制台应用程序,确实将数据(Json)发送到 Web Api

    // Get the stuff we need to send
    GetMetrics(out cpuTime, out memUsage, out totalMemory);

    // Send the data
    var postData = new
    {
       MachineName = System.Environment.MachineName,
       Processor = cpuTime,
       MemUsage = memUsage,
       TotalMemory = totalMemory
    };

    var json = JsonConvert.SerializeObject(postData);

    // Post the data to the server http://localhost:80/api/cpuinfo
    var serverUrl = new Uri(ConfigurationManager.AppSettings["ServerUrl"]);

    var client = new WebClient();
    client.Headers.Add("Content-Type", "application/json");
    client.UploadString(serverUrl, json);

移动到 Web 部件。我确实有 Asp.net MVC 并在 App_Start 中创建了 RouteConfig 以将 HTTP 请求路由到控制器。

        public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    } 

这是控制器类。

    public class CpuInfoController : ApiController
{
    public void Post(CpuInfoPostData cpuInfo)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<CpuInfo>();
        context.Clients.All.cpuInfoMessage(cpuInfo.MachineName, cpuInfo.Processor, cpuInfo.MemUsage, cpuInfo.TotalMemory);
    }
}

我还在 Global.asax 中注册了它,如下所示

        protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

完成所有这些之后,我仍然无法完成,我的控制台应用程序会弹出一些错误,如图所示。好像没有找到api/cpuinfo 。

如果我在这里做错了什么,请告诉我。这个项目的完整版本可以在这里找到。

标签: jsonpostasp.net-web-apimodel-view-controllersignalr

解决方案


您必须修改“CpuInfoClient”项目中的文件 App.config。(Key的值)

  1. 使用“http”而不是“https”
  2. 将端口号更改为启动后使用 Web 应用程序的实际端口号(而不是 44300)。当网络应用程序在 IE 或 Firefox 中启动时,您可以看到替换的确切端口。该端口也在“WcfCpuApp -> Properties -> Web -> Project-URL
  3. 当您启动“CpuInfoClient”时,请确保您的 Web 应用程序正在运行

推荐阅读