【发布时间】:2015-12-16 14:26:43
【问题描述】:
我是 ASP.Net Web API 的新手,想开发一个示例来获取日期时间。 我开发了两个应用程序。在第一个应用程序中,我有我的 API 并运行它抛出 Visual Studio,另一个是用于测试第一个的控制台应用程序。
在我的 API 上,我有:
public class DateTimeController : ApiController
{
public DateTime Get()
{
return DateTime.Now;
}
}
在我的控制台应用程序上我有这个,但我不知道它是否正确,因为它不起作用:
static void Main(string[] args)
{
string baseAddress = "http://localhost:13204/api/DateTime/get";
using (HttpClient httpClient = new HttpClient())
{
Task<String> response =
httpClient.GetStringAsync(baseAddress);
}
Console.ReadLine();
}
快速观看响应:
response.Status=WaitingForActivation
response.id=4
response.AsyncState=null
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "DateTime", action = "Get", id = UrlParameter.Optional }
);
}
}
【问题讨论】:
-
用
Get替换Getdate() -
@Ofiris 已更改但不起作用:(
-
更新您的问题以反映您没有在 URL 中包含括号,并显示您的路由(通常在 RouteConfig.cs 中)。最后,描述“不起作用”。你有错误吗?错误信息是什么?
-
你定制了web api路由配置吗?默认的 web api 路由配置应该有 /api/{controller}/{id}。基地址也应该是localhost:13204 和 httpClient.GetStringAsync("/api/DateTime/Get")
-
试试
http://localhost:13204/api/DateTime/Get
标签: c# asp.net asp.net-web-api asp.net-web-api2