json - 使用 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 。
如果我在这里做错了什么,请告诉我。这个项目的完整版本可以在这里找到。
解决方案
您必须修改“CpuInfoClient”项目中的文件 App.config。(Key的值)
- 使用“http”而不是“https”
- 将端口号更改为启动后使用 Web 应用程序的实际端口号(而不是 44300)。当网络应用程序在 IE 或 Firefox 中启动时,您可以看到替换的确切端口。该端口也在“WcfCpuApp -> Properties -> Web -> Project-URL
- 当您启动“CpuInfoClient”时,请确保您的 Web 应用程序正在运行
推荐阅读
- c# - C# 获取具有特定且完全匹配的扩展名的文件
- python - 调整现有代码和内核代码以执行大量 3x3 矩阵求逆
- cxf - 是否可以将 Apache CXF 与 Quarkus 一起使用,并进行本机编译?
- c - 如何解决这个 if else 语句?c prog
- google-api - 使用服务帐号为用户创建团队云端硬盘
- c# - ASP.Net Core 2.1 中间件 WindowsPrincipal ClaimsPrincipal
- java - 从不同的类调用同名方法
- geopandas - GeoViews:使用多边形几何图形向叶绿体添加滑块
- java - 无法通过 javaRDD 进行迭代器
- amazon-web-services - Amazon CloudFront URL 问题