问题
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 }
);
}
}
回答1:
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.
来源:https://stackoverflow.com/questions/34314570/how-to-get-date-and-time-on-asp-net-web-api