Owin搭建webapi服务器
项目版本:netframework 4.6.1
vs版本:vs2019
1、下载以下Nuget包:
Microsoft.AspNet.WebApi.Owin.5.2.7
Microsoft.AspNet.WebApi.Client.5.2.7
Microsoft.AspNet.WebApi.Core.5.2.7
Microsoft.Owin.2.1.0
Microsoft.Owin.Cors.2.1.0
Microsoft.Owin.FileSystems.2.1.0
Microsoft.Owin.Host.HttpListener.2.1.0
Microsoft.Owin.Hosting.2.1.0
Microsoft.Owin.StaticFiles.2.1.0
Owin.1.0
1、添加LogMiddleware日志记录扩展
public class LogMiddleware : OwinMiddleware { private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger(); public LogMiddleware(OwinMiddleware next) : base(next) { } public async override Task Invoke(IOwinContext context) { var request = context.Request; var requestBody = new StreamReader(request.Body).ReadToEnd(); var decryptedContent = new StringContent(requestBody, Encoding.UTF8, context.Request.ContentType); var requestStream = await decryptedContent.ReadAsStreamAsync(); request.Body = requestStream; var stream = context.Response.Body; var resBuffer = new MemoryStream(); context.Response.Body = resBuffer; await Next.Invoke(context); resBuffer.Seek(0, SeekOrigin.Begin); var resReader = new StreamReader(resBuffer); string responseBody = await resReader.ReadToEndAsync(); _logger.Debug($" url:【{context.Request.Path.Value}】;params:【{requestBody}】;result:【{responseBody}】"); resBuffer.Seek(0, SeekOrigin.Begin); await resBuffer.CopyToAsync(stream); } }
2、添加WebApi的配置
public class WebApiConfiguration { public static HttpConfiguration HttpConfig { get; private set; } public void Configuration(IAppBuilder app) { //app.UseStaticFiles(); //注册跨域请求许可 app.UseCors(CorsOptions.AllowAll); //注册中间件 app.Use<LogMiddleware>(); app.UseMiddleware(); var physicalFileSystem = new PhysicalFileSystem(@".\Test"); //静态网站根目录 var options = new FileServerOptions { EnableDefaultFiles = true, FileSystem = physicalFileSystem }; options.StaticFileOptions.FileSystem = physicalFileSystem; options.StaticFileOptions.ServeUnknownFileTypes = true; options.DefaultFilesOptions.DefaultFileNames = new[] { "Index.html" }; //默认页面(填写与静态网站根目录的相对路径) app.UseFileServer(options); //注册WebApi服务 var config = Register(); app.UseWebApi(config); } public static HttpConfiguration Register() { HttpConfig = new HttpConfiguration(); HttpConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver() { IgnoreSerializableAttribute = true }; HttpConfig.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); HttpConfig.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json")); HttpConfig.Formatters.JsonFormatter.SerializerSettings.Converters.Add( new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } ); HttpConfig.MapHttpAttributeRoutes(); HttpConfig.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional }); return HttpConfig; } }
3、添加启动管理
public class WebApiServer { public const string Started = "STARTED"; public const string Stopped = "STOPPED"; private static IDisposable _webApplication; public static string State { get; private set; } public static bool Run() { if (State == Started) return true; var url = $"http://+:9956"; // 限制只允许本机访问 //if (System.Diagnostics.Debugger.IsAttached) //{ // url = $"http://127.0.0.1:9956"; //} try { _webApplication = WebApp.Start<WebApiConfiguration>(url); } catch (Exception e) { return false; } State = Started; return true; } public static bool Stop() { if (State == Stopped) return true; try { _webApplication?.Dispose(); } catch (Exception e) { return false; } State = Stopped; return true; } }
4、调用
WebApiServer.Start(); WebApiServer.Stop();
奕独客》原创,转载请保留文章出处。
本文链接:Owin搭建webapi服务器 [https://www.yiduk.com/NET/36.html]
版权声明:若无特殊注明,本文为《正文到此结束