如何获得日期和时间上的ASP.Net的Web API? [英] How to get date and time on ASP.Net Web API?

查看:79
本文介绍了如何获得日期和时间上的ASP.Net的Web API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.Net的Web API新希望开发一个样本来获得日期和时间。
我开发了两个applications.In第一个我有我的API和运行它扔Visual Studio和另外一个是一个控制台应用程序来测试第一。

在我的API我有:

 公共类DateTimeController:ApiController
{
   公众获取的DateTime()
    {
        返回DateTime.Now;
    }
}

和我的控制台应用程序我有这个,但我不知道它的正确与否,因为它不工作:

 静态无效的主要(字串[] args)
    {
        字符串baseAddress =HTTP://本地主机:13204 / API /日期/获取;        使用(HttpClient的HttpClient的=新的HttpClient())
        {
            任务<串GT;响应=
             httpClient.GetStringAsync(baseAddress);        }
        到Console.ReadLine();
    }

这是响应快速的手表:
        response.Status = WaitingForActivati​​on结果
        response.id = 4
        response.AsyncState = NULL

WebApiConfig.cs

 公共静态无效的注册(HttpConfiguration配置)
    {
        //网页API的配置和服务        //网页API路线
        config.MapHttpAttributeRoutes();        config.Routes.MapHttpRoute(
            名称:DefaultApi
            routeTemplate:API / {}控制器/(编号),
            默认:新{ID = RouteParameter.Optional}
        );
    }

RouteConfig.cs

 公共类RouteConfig
{
    公共静态无效的RegisterRoutes(RouteCollection路线)
    {
        routes.IgnoreRoute({}资源个.axd / {*} PATHINFO);        routes.MapRoute(
            名称:默认,
            网址:{控制器} / {行动} / {ID}
            默认:新{控制器=日期时间,行动=获取,ID = UrlParameter.Optional}
        );
    }
}


解决方案

下面的几个问题。

HttpClient.GetStringAsync 返回任务<串> ,但你甚至不分配的结果给一个变量(或至少你没有当您第一次张贴的问题)。与返回任务的方法,你需要的await 他们或等待它们,直到任务完成。很多做在一个控制台应用程序方法这里描述 。我要选择一个,并告诉你如何实现它。

 静态无效的主要(字串[] args)
{
    VAR CTS =新CancellationTokenSource();    System.Console.CancelKey preSS + =(S,E)=>
    {
        e.Cancel =真;
        cts.Cancel();
    };    MainAsync(参数,cts.Token).Wait();
}静态异步任务MainAsync(字串[] args,令牌的CancellationToken)
{
    字符串baseAddress =HTTP://本地主机:13204 / API /日期;    使用(VAR的HttpClient =新的HttpClient())
    {
        字符串的响应=等待httpClient.GetStringAsync(baseAddress);
    }
}

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

注意,这是没有必要在URL中指定具体的操作方法,因为我们发送一个HTTP GET请求,并自该操作方法开始与获取的框架是足够聪明,知道它应该映射到操作方法。

I'm new on ASP.Net Web API and want to develop a sample to get date time. I developed two applications.In the first one i Have my API and run it throw Visual Studio and another one is a console application to test the first.

On my API I have:

public class DateTimeController : ApiController
{
   public DateTime Get()
    {
        return DateTime.Now;
    }
}

and on my Console application I have this,but i do not know it's correct or not because it doesn't work:

  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();
    }

Quick watch on response: 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 }
        );
    }
}

解决方案

Several issues here.

HttpClient.GetStringAsync returns a Task<string> but you are not even assigning the results to a variable (or at least you weren't when you first posted the question). With methods that return a Task, you need to await them or wait on them until the task is finished. A lot of methods for doing that in a console app are described here. I'm going to pick one and show you how to implement it.

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);
    }
}

The response variable will be a string that contains the datetime wrapped in JSON. You can then use your favorite JSON parsing library (I like Json.NET) to obtain the value.

Notice that it wasn't necessary to specify the specific action method in the URL, because we sent an HTTP GET request, and since that action method started with "Get" the framework is smart enough to know it should map to that action method.

这篇关于如何获得日期和时间上的ASP.Net的Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆