如何不使用ASP.NET在C#中创建REST服务及Windows语音合成REST API
Absolutely! You don’t need ASP.NET to build a REST API in C#—there are several lightweight, native, or alternative framework options that work perfectly for a text-to-speech (TTS) service. Let’s walk through a practical, dependency-light example that combines a REST endpoint with Windows’ built-in TTS functionality, using only .NET’s native libraries.
1. Using .NET's Native HttpListener for REST Services
The System.Net.HttpListener class is a built-in tool that lets you spin up a simple HTTP server without any web framework. It’s ideal for lightweight services like your TTS endpoint, since it avoids the overhead of ASP.NET.
First, you’ll need to ensure Windows HTTP Services are enabled (they usually are by default, but if you run into permissions issues, you may need to register the URL prefix with netsh—more on that later).
2. Integrating Windows Text-To-Speech
Windows includes a native TTS engine accessible via the System.Speech.Synthesis namespace. For .NET Framework projects, this is included by default; for .NET Core/.NET 5+, you’ll need to install the System.Speech NuGet package first.
3. Combined Example: REST Endpoint + TTS
Here’s a complete console application that creates a POST endpoint (http://localhost:8080/speak) to accept text, convert it to speech, and return a JSON response:
using System; using System.Net; using System.Text; using System.Text.Json; using System.Speech.Synthesis; using System.Threading.Tasks; class TtsRestService { static async Task Main(string[] args) { // Set up the listener to handle requests at http://localhost:8080/speak var listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/speak/"); try { listener.Start(); Console.WriteLine("TTS REST service running at http://localhost:8080/speak"); Console.WriteLine("Send a POST request with JSON body {\"text\": \"Your text here\"}"); } catch (HttpListenerException ex) { Console.WriteLine($"Failed to start service: {ex.Message}"); Console.WriteLine("Try running the app as administrator, or register the URL with:"); Console.WriteLine("netsh http add urlacl url=http://localhost:8080/speak/ user=YourUsername"); return; } // Keep the service running indefinitely while (true) { var context = await listener.GetContextAsync(); _ = HandleRequestAsync(context); // Process request in background } } static async Task HandleRequestAsync(HttpListenerContext context) { var request = context.Request; var response = context.Response; try { // Only accept POST requests if (request.HttpMethod != "POST") { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; await SendJsonResponse(response, new { error = "Only POST requests are supported" }); return; } // Read and parse the request body using var reader = new StreamReader(request.InputStream, request.ContentEncoding); var requestBody = await reader.ReadToEndAsync(); var ttsRequest = JsonSerializer.Deserialize<TtsRequest>(requestBody); if (string.IsNullOrWhiteSpace(ttsRequest?.Text)) { response.StatusCode = (int)HttpStatusCode.BadRequest; await SendJsonResponse(response, new { error = "Missing or empty 'text' field in request body" }); return; } // Convert text to speech using Windows' TTS engine using var synthesizer = new SpeechSynthesizer(); // Optional: Customize voice, volume, or rate // synthesizer.SelectVoiceByHints(VoiceGender.Female); // synthesizer.Volume = 80; synthesizer.Speak(ttsRequest.Text); // Return success response response.StatusCode = (int)HttpStatusCode.OK; await SendJsonResponse(response, new { success = true, message = $"Successfully spoke: {ttsRequest.Text}" }); } catch (Exception ex) { response.StatusCode = (int)HttpStatusCode.InternalServerError; await SendJsonResponse(response, new { error = $"Server error: {ex.Message}" }); } finally { response.Close(); } } static async Task SendJsonResponse(HttpListenerResponse response, object payload) { var json = JsonSerializer.Serialize(payload); var buffer = Encoding.UTF8.GetBytes(json); response.ContentType = "application/json"; response.ContentLength64 = buffer.Length; await response.OutputStream.WriteAsync(buffer, 0, buffer.Length); } } // Helper class to deserialize incoming requests public class TtsRequest { public string Text { get; set; } }
Key Notes:
- Permissions: If you get a "access denied" error when starting the service, run the app as administrator, or register the URL prefix with your user account using:
netsh http add urlacl url=http://localhost:8080/speak/ user=YourWindowsUsername - .NET Core/.NET 5+: Install the
System.SpeechNuGet package via the Package Manager Console:Install-Package System.Speech - Customization: You can tweak the TTS output by modifying the
SpeechSynthesizerinstance—select different voices, adjust volume, speech rate, or even save the output to a WAV file instead of speaking aloud.
Alternative: Lightweight Frameworks
If you want a more structured approach without ASP.NET, you could use frameworks like:
- NancyFX: A lightweight, convention-based web framework with minimal setup.
- ServiceStack: A full-featured but lightweight framework for building APIs (free for non-commercial use).
But the HttpListener example above is perfect for a simple, dependency-free TTS service.
内容的提问来源于stack exchange,提问作者Patrik Gfeller

