Program.cs•3.27 kB
using MCPDemo.Models;
using MCPDemo.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "MCP Demo API",
Version = "v1",
Description = "A .NET Web API implementing Model Context Protocol (MCP) server with Basic Authentication",
Contact = new Microsoft.OpenApi.Models.OpenApiContact
{
Name = "MCP Demo",
Email = "demo@example.com"
}
});
// Add Basic Authentication to Swagger
options.AddSecurityDefinition("Basic", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Name = "Authorization",
Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
Scheme = "basic",
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Description = "Basic Authorization header using the Bearer scheme. Enter 'admin' as username and 'password123' as password."
});
options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
{
{
new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Reference = new Microsoft.OpenApi.Models.OpenApiReference
{
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
Id = "Basic"
}
},
Array.Empty<string>()
}
});
// Include XML comments if available
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
{
options.IncludeXmlComments(xmlPath);
}
});
// Add MCP services
builder.Services.AddSingleton<IMcpServer, McpServer>();
// Add Basic Authentication
builder.Services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "MCP Demo API v1");
options.RoutePrefix = "swagger";
options.DocumentTitle = "MCP Demo API Documentation";
options.DefaultModelsExpandDepth(-1); // Hide schemas section by default
options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List);
options.EnableFilter();
options.EnableDeepLinking();
options.DisplayRequestDuration();
});
}
else
{
// Enable Swagger in production for demo purposes (normally you wouldn't do this)
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "MCP Demo API v1");
options.RoutePrefix = "swagger";
});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();