Search code examples
c#asp.net-web-api2owinself-host-webapi

OWIN Self-Host + Web Api connection cant make requests through Postman


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

Solution

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