【问题标题】:How to get date and time on ASP.Net Web API?如何在 ASP.Net Web API 上获取日期和时间?
【发布时间】: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


【解决方案1】:

这里有几个问题。

HttpClient.GetStringAsync 返回 Task&lt;string&gt; 但您甚至没有将结果分配给变量(或者至少在您第一次发布问题时没有分配)。对于返回任务的方法,您需要await 他们或等待他们直到任务完成。 here 描述了许多在控制台应用程序中执行此操作的方法。我将选择一个并向您展示如何实现它。

static void Main(string[] args)
{
    var cts = new CancellationTokenSource();

    System.Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        cts.Cancel();
    };

    MainAsync(args, cts.Token).Wait();
}

static async Task MainAsync(string[] args, CancellationToken token)
{
    string baseAddress = "http://localhost:13204/api/DateTime";

    using (var httpClient = new HttpClient())
    {
        string response = await httpClient.GetStringAsync(baseAddress);
    }
}

response 变量将是一个字符串,其中包含包裹在 JSON 中的日期时间。然后你可以使用你喜欢的 JSON 解析库(我喜欢Json.NET)来获取值。

请注意,没有必要在 URL 中指定特定的操作方法,因为我们发送了一个 HTTP GET 请求,并且由于该操作方法以“Get”开头,因此框架足够聪明,知道它应该映射到那个动作方法。

【讨论】:

  • 返回此错误:{"响应状态码不表示成功:404(未找到)。"}
  • @motevallizadeh 更新了 Web 服务的 URL。再试一次。
  • 你的意思是如果我在我的 URL 上输入 localhost:13204/api/DateTime/get 或类似的东西,它必须向我显示一些页面或结果哈?
  • @motevallizadeh 不,不要包含操作方法的名称。只需http://localhost:13204/api/DateTime
  • 如果我的 API 工作正常,它会在我的浏览器上显示日期吗?
猜你喜欢
  • 2012-11-28
  • 2016-02-03
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
相关资源
最近更新 更多