Simon
Simon

Reputation: 127

Start ASP.NET Core Web API from a Console App

I want to integrate a ASP.NET Core WebApi into a solution which consists of many other projects. (I use dotnet 6.0) Within the solution the WebAPI is started as Thread by the Main project. The problem is that if I run the WebApi from the other project only an empty WebApi is started. (Default Ports are used, not the configured one and there are no controllers...)

Can anybody help me?

This is a minimal soltution with the same problem I discribed above:

Solution structure

The WebApi is the default VisualStudio 2022 project. I only made small changes in the Program.cs file. This is the Code of the WebApi Project's Program.cs file:

namespace WebApi;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.

        builder.Services.AddControllers();
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();

        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
}

Code of the Programm.cs of the Main Project:

using WebApi;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
        WebApi.Program.Main(Array.Empty<string>());
    }
}

launchSettings.json

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:56423",
      "sslPort": 44385
    }
  },
  "profiles": {
    "WebApi": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7257;http://localhost:5257",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

This is how it looks if I run the WebApi from the Main project:

Hello, World!
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\data\Experimental\CallWebApiFromOtherProject\Main\bin\Debug\net6.0\

(Controllers and Swagger is not available. Also the ports are not the ones defined above. -> Only a Webserver without anything)

What I did wrong?

Upvotes: 2

Views: 9732

Answers (3)

vibs2006
vibs2006

Reputation: 6528

There are some things to be noted here (Applicable to .Net 6.0 and above)

If you just want to start API from command line (for example you want to unit test or use this API in your existing website app) then this is just a single line of code .

  1. Navigate to project folder of our API app (not where your .sln fils is location but your API app where your .csproj file is location.
  2. Open Command line and navigate to that folder. For example you need to navigate to D:\Projects\YourProject\src\YourApiFolder.
  3. open windows command line and navigate to that folder e.g cd D:\Projects\YourProject\src\YourApiFolder
  4. Execute simply dotnet run. Pl note that port number that will be used will be from your \YourApiFolder\Properties\LaunchSettings.json. You can edit this file and configure first profile in profiles json collection present in this file.
  5. Now open your normal visual studio solution and start using your normal debug mode or unit testing mode to test this API.

If you want to run this API from a console app(without even running dotnet run command) then you need to following steps

  1. Create a new console app, edit its .csproj file and change <Project Sdk="Microsoft.NET.Sdk"> to <Project Sdk="Microsoft.NET.Sdk.Web">. Reload your IDE. Please note that as soon your IDE will reload you'll see a folder created with name Properties which will have your default port details for kestral web server.
  2. Reference your existing API project
  3. Copy WebApplication builder code from program.cs in your existing API project in program.cs file here. Once you do that then you can simply execute this console exe after compiling and going to debug/release folder and it'll mimik functionality of dotnet run and will run separately like in case of dotnet run.

Upvotes: 1

Ruikai Feng
Ruikai Feng

Reputation: 11621

Some of the configration was lost because you start the webapi from other projects You could try as below in the main method of WebApi:

Directory.SetCurrentDirectory(@"the directory of WebApi Project");
var builder = WebApplication.CreateBuilder(new WebApplicationOptions() { EnvironmentName= "Development",ApplicationName="WebApi"});

Now,it works well in my case:

enter image description here

Upvotes: 4

Amogh Sarpotdar
Amogh Sarpotdar

Reputation: 617

What you are trying to achieve is well documented here (and it is called as selfhosting) -

https://www.c-sharpcorner.com/UploadFile/2b481f/self-hosting-in-Asp-Net-web-api/

You can host the webAPI in different ways - what you are trying to do is one of the ways, where the API is hosted as a standalone application instead of in a web server.

Please note that selfhosting changes the way configuration is being loaded. One of the important point to remember is that -

If you self-host Web API, you must set the routing table directly on the HttpSelfHostConfiguration object. For more information, see Self-Host a Web API.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api#:~:text=If%20you%20self%2Dhost%20Web%20API%2C%20you%20must%20set%20the%20routing%20table%20directly%20on%20the%20HttpSelfHostConfiguration%20object.%20For%20more%20information%2C%20see%20Self%2DHost%20a%20Web%20API.

Upvotes: 0

Related Questions