how to create asp.net self-hosted web api
Loading
how to create asp.net self-hosted web api
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sangeetha SRank #212 · 11.4K reputationPosted May 7, 2025, 1:09 AM EDT
Self-hosted ASP.NET Core Web API:
Open a terminal or Visual Studio and run:
dotnet new webapi -n MySelfHostedApi
cd MySelfHostedApi
In
.NET 6/7/8, theProgram.csfile already sets up Kestrel by default:var builder = WebApplication.CreateBuilder(args);
// Add services
builder.Services.AddControllers();
var app = builder.Build();
// Configure middleware
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run(); // This starts the Kestrel server
press F5 in Visual Studio.
Use a browser or tool like Postman or
curl:curl http://localhost:8080/weatherforecast
Daniel WrightRank #2,947 · 489 reputationPosted May 6, 2025, 5:53 PM EDT
Creating a self-hosted ASP.NET Web API allows you to host your API within your application instead of relying on IIS. This can be beneficial for certain scenarios where you want more control or flexibility over how your API is hosted.
To create a self-hosted ASP.NET Web API, you can follow these steps:
1. Create a new ASP.NET Web API Project:
Start by creating a new ASP.NET Web API project in Visual Studio.
2. Install the required NuGet packages:
You will need to install the necessary NuGet packages for self-hosting. The main package you'll need is `Microsoft.AspNet.WebApi.SelfHost`.
3. Configure Web API routes:
Set up your Web API routes in the `WebApiConfig.cs` file. Define your routes based on the API endpoints you want to expose.
4. Create a self-hosting server:
In your `Program.cs` or any startup file, you can create a self-hosting server using `HttpSelfHostConfiguration`:
var config = new HttpSelfHostConfiguration("http://localhost:8080"); config.Routes.MapHttpRoute( name: "API", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); using (HttpSelfHostServer server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Web API Self-hosted on http://localhost:8080"); Console.ReadLine(); }5. Run your self-hosted Web API:
When you run your application, the Web API will be hosted on the specified URL (e.g., `http://localhost:8080`). You can then make HTTP requests to test your API endpoints.
By following these steps, you can successfully create a self-hosted ASP.NET Web API. This approach gives you more flexibility in how you host your API and can be useful in certain scenarios. If you have any specific questions or need further clarification, feel free to ask!