0

I am trying to self-host Web API. It works fine when I call requests through my program, where is API controller. But i can't make request through Postman Client. What could be the problem?

Api Controller

public class MyApiController : ApiController
{
    public string Get()
    {
        return "Get";
    }
}

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        appBuilder.UseWebApi(config);
    }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        string url = "http://localhost:44300/";
        using (WebApp.Start<Startup>(url))
        {
            var client = new HttpClient();

            var response = client.GetAsync(url + "api/myapi").Result;

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
        }
        Console.ReadLine();
    }
}
Raghu Ariga
  • 1,059
  • 1
  • 19
  • 28
MikeSFive
  • 3
  • 3
  • Are you trying to read the api at the same program you host it? – Fals Jan 13 '17 at 21:12
  • Can you please post the request you are using to call `Get()`? – Stephen Reindl Jan 13 '17 at 21:29
  • When you say you cant make a request through postman, what error code does postman give you? – Chris Watts Jan 13 '17 at 21:34
  • The host is disposed of before any other requests can be made. move the `Console.ReadLine` to within the `using` block and that should force the program to wait for input and keep the host active. – Nkosi Jan 14 '17 at 10:25

1 Answers1

0

It looks like your issues are in your main method. In C#, the using statement (link) creates a resource, executes the code in the block, and then disposes of the resource.

In your posted example, your WebApp is disposed right after it prints the response to the console (and before you're able to make requests with your browser).

These edits should allow you to keep the WebApp in-scope in order to play around with the framework.

class Program
{
    static void Main(string[] args)
    {
        string url = "http://localhost:44300/";
        using (WebApp.Start<Startup>(url))
        {
            var client = new HttpClient();

            var response = client.GetAsync(url + "api/myapi").Result;

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            Console.WriteLine("WebApp Ready");
            Console.ReadLine();
        }
        Console.WriteLine("WebApp disposed.");
        Console.ReadLine();
    }
}
Garrett Clyde
  • 306
  • 3
  • 9