How to setup console self-host project for an exis

2019-08-26 12:57发布

问题:

I have ASP.NET web application. The template creates default web api controller ValuesController. I am trying to create console application to self-host using Microsoft.AspNet.WebApi.OwinSelfHost version 5.2.6. Solution structure looks like:

Startup.cs in SelfHost.Server, agree! not a good name, is looks like:

HttpConfiguration config = new HttpConfiguration();

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional });

        app.UseWebApi(config);

And this is how I am using it:

static void Main(string[] args)
    {
        var uri = "http://localhost:44382/";
        using (WebApp.Start<Startup>(uri))
        {
            Console.WriteLine($"Server started at {uri} on {DateTime.Now}");

            HttpClient client = new HttpClient();
            var response = client.GetAsync(uri + "api/values").Result;
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);

            Console.ReadKey();
        }
    }

Running console application gives this error:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:44382/api/values'.","MessageDetail":"No type was found that matches the controller named 'values'."}

Using postman I get "Could not get any response"

Question Please, how can I do this?

回答1:

Regardless of the question if we should be doing it or not. There are many ways but here are the steps I followed: (Created new projects which are named different as in original question)

Create web api project WebApplication1 (I used existing template in visual studio). Create console app, ConsoleApp1. Add reference of WebApplication1 into ConsoleApp1. Add Microsoft.AspNet.WebApi.OwinSelfHost nuget package to ConsoleApp1. Update main method in program.cs as:

var baseAddress = "http://localhost: 44358/";
        using (WebApp.Start<Startup>(baseAddress))
        {
            Console.WriteLine("Server started at:" + baseAddress);
            Console.ReadLine();
        }

Add startup.cs to ConsoleApp1 put following code in it:

public void Configuration(IAppBuilder app)
    {
        // Configure Web API for self-host.
        var config = new HttpConfiguration();
        WebApplication1.WebApiConfig.Register(config);
        app.UseWebApi(config);
    }

Use postman or any client to test endpoint http://localhost:44358/api/values

Conclusion: We can do it. I used configurations from WebApplication1 into ConsoleApp1. Similarly, other configuration e.g. unity, filters etc can be reused if required.

Sample output (using postman):