1

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 }
        );
    }
}
motevalizadeh
  • 5,244
  • 14
  • 61
  • 108
  • Replace `Getdate()` with `Get` – Ofiris Dec 16 '15 at 14:29
  • @Ofiris Changed it but does not work :( – motevalizadeh Dec 16 '15 at 14:38
  • 1
    Update your question to reflect that you're not including the parantheses in the URL, and also show your routing (usually in RouteConfig.cs). And lastly, describe "does not work". Do you get an error? What is the error message? – mason Dec 16 '15 at 14:39
  • have you customized web api routing config? default web api routing config should have /api/{controller}/{id}. Also base address should be http://localhost:13204 and httpClient.GetStringAsync("/api/DateTime/Get") – Deepu Madhusoodanan Dec 16 '15 at 14:47
  • Try `http://localhost:13204/api/DateTime/Get` – Sybren Dec 16 '15 at 14:48
  • Sorry, I was mistaken in my previous comment. We just need WebApiConfig.cs. Not RouteConfig.cs (which is for MVC routes). – mason Dec 16 '15 at 14:53
  • how can i test my API works fine? without another application i mean – motevalizadeh Dec 16 '15 at 15:24
  • You would just navigate to the exposed endpoint with your browser to test a GET request. But a common tool for testing these with Google Chrome is [Postman](https://www.getpostman.com/), which supports more than just GET and POST requests. – mason Dec 16 '15 at 15:40

1 Answers1

2

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.

Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121
  • Return this error: {"Response status code does not indicate success: 404 (Not Found)."} – motevalizadeh Dec 16 '15 at 15:23
  • @motevallizadeh Updated URL to the web service. Try again. – mason Dec 16 '15 at 15:26
  • You mean if i enter http://localhost:13204/api/DateTime/get or something like it on my URL it must show me some page or result ha? – motevalizadeh Dec 16 '15 at 15:28
  • @motevallizadeh No, do not include the name of the action method. Just `http://localhost:13204/api/DateTime` – mason Dec 16 '15 at 15:29
  • if my API works fine it will show me the date on my browser? – motevalizadeh Dec 16 '15 at 15:30
  • @motevallizadeh If you type that URL into your browser, you should see the date delivered as XML or JSON. If you access it via HttpClient from your console app like I've shown, the result should be stored in `response` variable. – mason Dec 16 '15 at 15:31
  • i can not understand that why we do not use action name, i mean every controller has a one method to get data and compiler will find the action name by itself? – motevalizadeh Dec 16 '15 at 15:34
  • @motevallizadeh I gave a brief explanation of that in my answer. The framework is smart enough to map it to the `Get` action method because you sent an HTTP GET request and that action method's name started with "get" and the parameters lined up (because there are no parameters in the URL and that action method requires none). Fore more detail, see [Routing and Action Selection in ASP.NET Web API](http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection). – mason Dec 16 '15 at 15:38