在.NET Framework环境中模拟启动Web服务,可以使用几种不同的方法。一个常见的选择是利用HttpListener类来创建一个简单的HTTP服务器,或者使用Owin/Katana库来自托管ASP.NET Web API或MVC应用。下面简要介绍Owin/Katana示例代码。这种方法更加灵活,并且可以让你充分利用ASP.NET的特性和功能,比如模型绑定、过滤器、依赖注入等。同时它也支持通过配置文件进行更复杂的设置。
1.安装依赖包
Microsoft.Owin.Host.HttpListener
Microsoft.AspNet.WebApi.OwinSelfHost(如果你要用到Web API)
2.在Program.cs文件中配置web服务
using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Web.Http;namespace SelfHostedWebApi
{class Startup{// 配置Web API路由和其他设置public void Configuration(IAppBuilder appBuilder){HttpConfiguration config = new HttpConfiguration();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}",defaults: new { id = RouteParameter.Optional });appBuilder.UseWebApi(config);}}class Program{static IDisposable _webApp;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);// 启动Web API服务string baseAddress = "http://*:9005/";_webApp = WebApp.Start<Startup>(url: baseAddress);Console.WriteLine($"Web API running at {baseAddress}");// 启动WinForms应用程序Application.Run(new MainForm());// 可选:添加其他中间件,例如静态文件支持、跨域资源共享(CORS)等// appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);// 停止Web API服务//_webApp.Dispose();}}
}
3.编写webapi服务
这里比如我们去写一个接收文件的api接口,访问时可直接访问http://ip:9005/api/Files/post
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Newtonsoft.Json.Linq; // 引用Newtonsoft.Json库namespace SelfHostedWebApi.Controllers
{public class FilesController : ApiController{private readonly string _fileStoragePath = @"C:\File";// POST api/files[HttpPost]public async Task<HttpResponseMessage> Post(){// 检查请求是否包含 multipart/form-data 内容类型if (!Request.Content.IsMimeMultipartContent()){return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);}try{var provider = new MultipartMemoryStreamProvider();await Request.Content.ReadAsMultipartAsync(provider);foreach (var file in provider.Contents){var filename = file.Headers.ContentDisposition.FileName.Trim('\"');var buffer = await file.ReadAsByteArrayAsync();// 判断文件是否为.json格式if (filename.EndsWith(".json", StringComparison.OrdinalIgnoreCase)){// 将字节数组转换为字符串string jsonString = System.Text.Encoding.UTF8.GetString(buffer);// 解析JSON字符串dynamic jsonData = JObject.Parse(jsonString);// 处理接收到的JSON数据string message = $"Received JSON data with key 'name': {jsonData.name}";return Request.CreateResponse(HttpStatusCode.OK, new { Message = message });}else{// 如果不是JSON文件,则保存到本地磁盘if (!Directory.Exists(_fileStoragePath)){Directory.CreateDirectory(_fileStoragePath);}var localFilePath = Path.Combine(_fileStoragePath, filename);File.WriteAllBytes(localFilePath, buffer);return Request.CreateResponse(HttpStatusCode.Created, new { FilePath = localFilePath });}}return Request.CreateResponse(HttpStatusCode.BadRequest, "No files found.");}catch (Exception ex){return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);}}}
}