Json 使用Post方法向Web Api传递数据返回:远程服务器返回错误:(404)未找到
最近,我刚开始学习SignalR,我一直在测试我在GitHub上找到的一个。然而,当我试图将数据发布到Web api部件时,我确实遇到了问题 我只是把所有的事情都做完了,但我真的无法让这个项目以某种方式运作。这基本上是该项目的计划。它是一个控制台应用程序,确实将数据(Json)发送到Web ApiJson 使用Post方法向Web Api传递数据返回:远程服务器返回错误:(404)未找到,json,post,asp.net-web-api,model-view-controller,signalr,Json,Post,Asp.net Web Api,Model View Controller,Signalr,最近,我刚开始学习SignalR,我一直在测试我在GitHub上找到的一个。然而,当我试图将数据发布到Web api部件时,我确实遇到了问题 我只是把所有的事情都做完了,但我真的无法让这个项目以某种方式运作。这基本上是该项目的计划。它是一个控制台应用程序,确实将数据(Json)发送到Web Api // Get the stuff we need to send GetMetrics(out cpuTime, out memUsage, out totalMemory);
// 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);
}
}
完成所有这些之后,我仍然无法完成这项工作,我的控制台应用程序会弹出一些错误,如图所示。似乎未找到api/cpuinfo
如果我在这里做错了什么,请告诉我。
可以找到此项目的完整版本。您必须修改“CpuInfoClient”项目中的App.config文件。(键的值)
您必须修改“CpuInfoClient”项目中的App.config文件。(键的值)
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}