yz_server/Server/OwinServer.cs

237 lines
8.0 KiB
C#

using Microsoft.AspNetCore.Cors;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.StaticFiles;
using Newtonsoft.Json;
using Owin;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
namespace Server
{
internal class OwinServer
{
public static string RootDir = CsharpHttpHelper.HttpExtend.MapPath("网站");// Directory.GetCurrentDirectory() + "\\网站";
/// <summary>
/// 查找本地数据,无数据 返回index
/// </summary>
/// <param name="relPath"></param>
/// <returns></returns>
public static string GetFilePath(string relPath)
{
if (string.IsNullOrEmpty(relPath) || relPath == "/")
{
relPath = "index.html";
}
return Path.Combine(
AppDomain.CurrentDomain.BaseDirectory
, RootDir
, relPath.TrimStart('/').Replace('/', '\\'));
}
/// <summary>
/// 设置返回contenttype 并返回数据
/// </summary>
/// <param name="context"></param>
/// <param name="path"></param>
/// <returns></returns>
public Task SetResponse(IOwinContext context, string path)
{
var perfix = Path.GetExtension(path);
switch (perfix)
{
case ".html":
context.Response.ContentType = "text/html; charset=utf-8";
break;
case ".js":
context.Response.ContentType = "application/x-javascript";
break;
case ".css":
context.Response.ContentType = "text/css";
break;
case ".jpg":
case ".jpeg":
context.Response.ContentType = "image/jpeg";
break;
case ".png":
context.Response.ContentType = "application/x-png";
break;
case ".mp4":
context.Response.ContentType = "video/mpeg4";
break;
case ".webp":
context.Response.ContentType = "image/webp";
break;
case ".gif":
context.Response.ContentType = "image/gif";
break;
case ".woff2":
context.Response.ContentType = "application/x-font-woff";
break;
case ".ico":
context.Response.ContentType = "image/x-icon";
break;
}
return context.Response.WriteAsync(File.ReadAllText(path));
}
/// <summary>
/// 执行API
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
private Task TodoApi(IOwinContext context, Func<Task> next)
{
//var response = new WebResult();
//try
//{
// var query = context.Request.Query.ToString();
// //Dictionary<string, string> Param = new Dictionary<string, string>();
// //var contentType = context.Request.ContentType;
// //if (context.Request.Method.ToLower() == "post")
// //{
// // if (contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
// // {
// // string body = new StreamReader(context.Request.Body, Encoding.UTF8).ReadToEnd();
// // var postdata =new NameValueCollection(StringComparer.OrdinalIgnoreCase);
// // ///Util.GetQueryString(body, Encoding.UTF8);
// // if (postdata != null)
// // {
// // foreach (var item in postdata.AllKeys)
// // {
// // Param[item] = HttpUtility.UrlEncode(postdata[item]);
// // }
// // }
// // }
// //}
// //if (context.Request.Query != null && context.Request.Query.Count() > 0)
// //{
// // foreach (var item in context.Request.Query)
// // {
// // if (item.Value != null && item.Value.Length > 0) Param[item.Key] = HttpUtility.UrlDecode(item.Value[0]);
// // }
// //}
// //if (EventClient.StopParsing) return next();
// //var plugins = PluginClient.Plugins.ToArray();
// //var events = new WebRequestEvents(context, Param, response);
// ////正常事件解析
// //foreach (var plugin in plugins)
// //{
// // if (!plugin.IsRun) continue;//未运行
// // if (events.Cancel) break;//已取消传递
// // plugin.SDK.OnEvent(context, events);
// //}
//}
//catch (Exception ex)
//{
// response.code = -1;
// response.errMsg = ex.Message;
//}
//if (string.IsNullOrEmpty(response.))
//{
// response.ok = false;
// response.errMsg = $"请求成功,但未响应结果!{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
//}
//var msg = JsonConvert.SerializeObject(response);
context.Response.StatusCode = (int)HttpStatusCode.OK;
return context.Response.WriteAsync("无响应结果");
}
/// <summary>
/// 挂载数据 分流静态文件及接口请求
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
public async Task RequestHandler(IOwinContext context, Func<Task> next)
{
try
{
var path = GetFilePath(context.Request.Path.Value);
if (File.Exists(path))
{
await SetResponse(context, path);
}
else
{
await TodoApi(context, next);
}
}
catch (Exception)
{
}
await next();
}
public void Configuration(Owin.IAppBuilder appBuilder)
{
appBuilder.UseCors(CorsOptions.AllowAll);
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}"
//);
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { controller = "abbb", action = "Index", id = UrlParameter.Optional }
);
///@".\wwwroot"
var physicalFileSystem = new PhysicalFileSystem(RootDir);
var options = new FileServerOptions
{
EnableDefaultFiles = true,
FileSystem = physicalFileSystem
};
options.StaticFileOptions.FileSystem = physicalFileSystem;
options.StaticFileOptions.ServeUnknownFileTypes = true;
options.DefaultFilesOptions.DefaultFileNames = new[] { "Index.html" };
appBuilder.UseFileServer(options);
appBuilder.UseWebApi(config);
/*
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
*/
}
}
}