Add RoslynBridge.WebApi - ASP.NET Core 8.0 middleware that: - Provides a centralized REST API for accessing multiple VS instances - Manages instance registry with discovery by port, solution, or PID - Proxies requests to the appropriate VS instance - Tracks request/response history for debugging - Auto-cleanup of stale instances via background service Features: - Health endpoints: /api/health, /api/health/ping - Roslyn endpoints: /api/roslyn/projects, /api/roslyn/diagnostics, etc. - Instance management: /api/instances (register, heartbeat, unregister) - History tracking: /api/history, /api/history/stats - Swagger UI at root (/) for API documentation - CORS enabled for web applications Services: - InstanceRegistryService: Thread-safe registry of VS instances - HistoryService: In-memory request/response history (max 1000 entries) - InstanceCleanupService: Background service to remove stale instances - RoslynBridgeClient: HTTP client for proxying to VS instances Update RoslynBridge.sln to include RoslynBridge.WebApi project. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
9.4 KiB
Roslyn Bridge Web API
A modern ASP.NET Core web API that acts as middleware between Claude AI and the Roslyn Bridge Visual Studio plugin, providing RESTful access to C# code analysis capabilities.
Overview
This web API serves as a bridge between external clients (like Claude AI) and the Visual Studio Roslyn Bridge plugin. It provides:
- Modern RESTful API with comprehensive Swagger/OpenAPI documentation
- CORS-enabled for web application access
- Health monitoring for both the web API and Visual Studio plugin connection
- Simplified endpoints for common Roslyn operations
- Type-safe models with validation
Architecture
┌─────────────┐ HTTP/REST ┌──────────────────┐ HTTP ┌─────────────────────┐
│ Claude │ ◄─────────────────► │ Web API (5000) │ ◄────────────► │ VS Plugin (59123) │
│ AI │ │ Middleware │ │ Roslyn Bridge │
└─────────────┘ └──────────────────┘ └─────────────────────┘
Getting Started
Prerequisites
- .NET 8.0 SDK or later
- Visual Studio with Roslyn Bridge plugin running (default port: 59123)
Quick Installation
Option 1: Automated Installation
Open PowerShell as Administrator:
cd RoslynBridge.WebApi
.\install.ps1 -InstallService -StartService
This will build, publish, install as a Windows Service, and start the API automatically.
For more detailed service setup options, see SERVICE_SETUP.md.
Option 2: Development Mode
-
Start the Visual Studio plugin (it should be running on port 59123)
-
Run the Web API:
cd RoslynBridge.WebApi dotnet run -
Access Swagger UI:
- Navigate to:
http://localhost:5000 - Or:
https://localhost:7001(with HTTPS)
- Navigate to:
Configuration
Edit appsettings.json to configure the connection:
{
"RoslynBridge": {
"BaseUrl": "http://localhost:59123",
"TimeoutSeconds": 30
}
}
API Endpoints
Health Endpoints
- GET /api/health - Check health status of Web API and VS plugin
- GET /api/health/ping - Simple ping endpoint
Roslyn Query Endpoints
- POST /api/roslyn/query - Execute any Roslyn query
- GET /api/roslyn/projects - Get all projects in solution
- GET /api/roslyn/solution/overview - Get solution statistics
- GET /api/roslyn/diagnostics - Get errors and warnings
- GET /api/roslyn/symbol - Get symbol information at position
- GET /api/roslyn/references - Find all references to symbol
- GET /api/roslyn/symbol/search - Search for symbols by name
Refactoring Endpoints
- POST /api/roslyn/format - Format a document
- POST /api/roslyn/project/package/add - Add NuGet package
- POST /api/roslyn/project/build - Build a project
Example Usage
Using curl
# Health check
curl http://localhost:5000/api/health
# Get all projects
curl http://localhost:5000/api/roslyn/projects
# Get solution overview
curl http://localhost:5000/api/roslyn/solution/overview
# Execute custom query
curl -X POST http://localhost:5000/api/roslyn/query \
-H "Content-Type: application/json" \
-d '{
"queryType": "getsymbol",
"filePath": "C:\\path\\to\\file.cs",
"line": 10,
"column": 5
}'
# Search for symbols
curl "http://localhost:5000/api/roslyn/symbol/search?symbolName=MyClass"
# Get diagnostics
curl "http://localhost:5000/api/roslyn/diagnostics"
Using JavaScript/TypeScript
const response = await fetch('http://localhost:5000/api/roslyn/query', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
queryType: 'getprojects'
})
});
const result = await response.json();
console.log(result.data);
Using C#
using var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:5000");
var request = new RoslynQueryRequest
{
QueryType = "getsolutionoverview"
};
var response = await client.PostAsJsonAsync("/api/roslyn/query", request);
var result = await response.Content.ReadFromJsonAsync<RoslynQueryResponse>();
Query Types
The following query types are supported:
Code Analysis
getprojects- Get all projectsgetdocument- Get document informationgetsymbol- Get symbol at positiongetsemanticmodel- Get semantic modelgetsyntaxtree- Get syntax treegetdiagnostics- Get compilation errors/warningsfindreferences- Find all referencesfindsymbol- Find symbols by namegettypemembers- Get type membersgettypehierarchy- Get type hierarchyfindimplementations- Find implementationsgetnamespacetypes- Get namespace typesgetcallhierarchy- Get call hierarchygetsolutionoverview- Get solution overviewgetsymbolcontext- Get symbol contextsearchcode- Search code patterns
Refactoring
formatdocument- Format documentorganizeusings- Organize using statementsrenamesymbol- Rename symboladdmissingusing- Add missing usingapplycodefix- Apply code fix
Project Operations
addnugetpackage- Add NuGet packageremovenugetpackage- Remove NuGet packagebuildproject- Build projectcleanproject- Clean projectrestorepackages- Restore packagescreatedirectory- Create directory
Response Format
All responses follow this structure:
{
"success": true,
"message": "Optional message",
"data": { ... },
"error": null
}
Error responses:
{
"success": false,
"message": null,
"data": null,
"error": "Error description"
}
Features
CORS Support
The API is configured with CORS enabled for all origins, making it accessible from web applications.
Swagger/OpenAPI
Comprehensive API documentation is available at the root URL (/) with:
- Detailed endpoint descriptions
- Request/response models
- Try-it-out functionality
- XML documentation comments
Health Checks
Built-in health checks monitor:
- Web API service status
- Visual Studio plugin connectivity
- Request/response timing
Logging
Structured logging with different levels:
- Information: General operations
- Warning: Non-critical issues
- Error: Failed operations
- Debug: Detailed tracing (Development only)
Development
Project Structure
RoslynBridge.WebApi/
├── Controllers/
│ ├── HealthController.cs # Health check endpoints
│ └── RoslynController.cs # Roslyn operation endpoints
├── Models/
│ ├── RoslynQueryRequest.cs # Request DTOs
│ ├── RoslynQueryResponse.cs # Response DTOs
│ └── HealthCheckResponse.cs # Health check models
├── Services/
│ ├── IRoslynBridgeClient.cs # Client interface
│ └── RoslynBridgeClient.cs # HTTP client implementation
├── Program.cs # Application configuration
├── appsettings.json # Configuration
└── README.md # This file
Building
dotnet build
Running Tests
dotnet test
Publishing
dotnet publish -c Release -o ./publish
Deployment
Docker (Optional)
Create a Dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 5000
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["RoslynBridge.WebApi.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet build -c Release -o /app/build
FROM build AS publish
RUN dotnet publish -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RoslynBridge.WebApi.dll"]
Build and run:
docker build -t roslyn-bridge-api .
docker run -p 5000:5000 roslyn-bridge-api
Integration with Claude
This API is designed to work seamlessly with Claude AI for code analysis tasks:
- Claude can query project structure
- Analyze code for errors and warnings
- Search for symbols and references
- Suggest refactorings
- Navigate code hierarchies
Example Claude prompt:
"Using the Roslyn Bridge API at http://localhost:5000,
analyze the current solution and identify any code quality issues."
Troubleshooting
Visual Studio Plugin Not Connected
Error: {"vsPluginStatus": "Disconnected"}
Solution:
- Ensure Visual Studio is running
- Verify Roslyn Bridge plugin is installed and active
- Check plugin is listening on port 59123
- Update
appsettings.jsonif using a different port
CORS Errors
If accessing from a web app:
- Verify CORS is enabled in
Program.cs - Check browser console for specific CORS errors
- Ensure the origin is allowed
Timeout Errors
Increase timeout in appsettings.json:
{
"RoslynBridge": {
"TimeoutSeconds": 60
}
}
License
This project is part of the Roslyn Bridge suite.
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
Support
For issues and questions:
- Check the Swagger documentation at
/ - Review the logs in the console output
- Verify the Visual Studio plugin is running