首页 > 其他分享 >自宿主web服务器搭建记录

自宿主web服务器搭建记录

时间:2024-06-04 19:13:19浏览次数:13  
标签:perfix web ConfigTool 宿主 application context 服务器 using Response

建立3个项目,分别是类库WebSite、控制台TestWebSite、win服务WinService,目标框架均为.NET Framework 4.8.1。

其中控制台方便开发调试,win服务作为宿主服务,类库为自定义webservice的主体代码。

TestWebSite和WinService 引用nuget包 Microsoft.Owin.Host.HttpListener  4.2.2,不然启动的时候会提示错误消息:

The server factory could not be located for the given input

WebSite引用nuget包:

Microsoft.AspNet.Cors
Microsoft.AspNet.WebApi.Core
Microsoft.Owin
Microsoft.AspNet.WebApi.Owin
Microsoft.AspNet.WebApi.Cors
Microsoft.AspNet.WebApi.WebHost
Microsoft.AspNet.WebApi.SelfHost
Microsoft.Owin.Host.HttpListener
Microsoft.Owin.Hosting
Newtonsoft.Json

在WebSite中增加目录Controllers和wwwroot

using System;
using System.Web.Http;

namespace ConfigTool.WebSite.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : ApiController
    {
        [HttpGet]
        [Route("Time")]
        public string Time()
        {
            return DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        }

    }
}

在wwwroot下放入index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
    <p>
        <input type="text" id="curtime" value="1"/>
        <button id="submit">从api接口获取当前服务器时间</button>
    </p>
    <p>
        <image src="images/1.jpg" alt="验证静态资源" width="300" height="300"/>
    </p>
</body>

<script>
    $("#submit").click(function(){
        $.get("api/Values/Time",function(data,status){    
            $("#curtime").val(data);
        });
    });
</script>
</html>

新增Startup类文件

using Microsoft.Owin;
using Owin;
using System;
using System.IO;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;


namespace ConfigTool.WebSite
{
    internal class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = InitWebApiConfig();
            app.UseWebApi(config);
            //静态文件
            app.Use((context, fun) =>
            {
                return StaticFileHandler(context, fun);
            });
        }

        /// <summary>
        /// 路由初始化
        /// </summary>
        HttpConfiguration InitWebApiConfig()
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "api/{controller}/{action}",
                defaults: new { id = RouteParameter.Optional }
            );

            var cors = new EnableCorsAttribute("*", "*", "*");//跨域允许设置
            config.EnableCors(cors);

            config.Formatters
               .XmlFormatter.SupportedMediaTypes.Clear();
            //默认返回json
            config.Formatters
                .JsonFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("datatype", "json", "application/json"));

            config.Formatters
                .XmlFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("datatype", "xml", "application/xml"));

            config.Formatters
                .JsonFormatter.SerializerSettings = new
                Newtonsoft.Json.JsonSerializerSettings()
                {
                    DateFormatString = "yyyy-MM-dd HH:mm:ss"
                };
            return config;
        }

        /// <summary>
        /// 客户端请求静态文件处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public Task StaticFileHandler(IOwinContext context, Func<Task> next)
        {
            //获取物理文件路径
            var path = GetFilePath(context.Request.Path.Value);
            //验证路径是否存在
            if (!File.Exists(path) && !path.EndsWith("html"))
            {
                path += ".html";
            }
            if (File.Exists(path))
            {
                return StaticFileResponse(context, path);
            }
            //不存在,返回下一个请求
            return next();
        }

        static string GetFilePath(string path)
        {
            var basePath = AppDomain.CurrentDomain.BaseDirectory;
            var filePath = path.TrimStart('/').Replace('/', '\\');
            return Path.Combine(basePath, "wwwroot", filePath);
        }

        Task StaticFileResponse(IOwinContext context, string path)
        {
            /*
                .txt text/plain
                RTF文本 .rtf application/rtf
                PDF文档 .pdf application/pdf
                Microsoft Word文件 .word application/msword
                PNG图像 .png image/png
                GIF图形 .gif image/gif
                JPEG图形 .jpeg,.jpg image/jpeg
                au声音文件 .au audio/basic
                MIDI音乐文件 mid,.midi audio/midi,audio/x-midi
                RealAudio音乐文件 .ra, .ram audio/x-pn-realaudio
                MPEG文件 .mpg,.mpeg video/mpeg
                AVI文件 .avi video/x-msvideo
                GZIP文件 .gz application/x-gzip
                TAR文件 .tar application/x-tar
                任意的二进制数据 application/octet-stream
             */
            var perfix = Path.GetExtension(path);
            if (perfix == ".html")
                context.Response.ContentType = "text/html; charset=utf-8";
            else if (perfix == ".txt")
                context.Response.ContentType = "text/plain";
            else if (perfix == ".js")
                context.Response.ContentType = "application/x-javascript";
            else if (perfix == ".css")
                context.Response.ContentType = "text/css";
            else
            {
                if (perfix == ".jpeg" || perfix == ".jpg")
                    context.Response.ContentType = "image/jpeg";
                else if (perfix == ".gif")
                    context.Response.ContentType = "image/gif";
                else if (perfix == ".png")
                    context.Response.ContentType = "image/png";
                else if (perfix == ".svg")
                    context.Response.ContentType = "image/svg+xml";
                else if (perfix == ".woff")
                    context.Response.ContentType = "application/font-woff";
                else if (perfix == ".woff2")
                    context.Response.ContentType = "application/font-woff2";
                else if (perfix == ".ttf")
                    context.Response.ContentType = "application/octet-stream";
                else
                    context.Response.ContentType = "application/octet-stream";

                return context.Response.WriteAsync(File.ReadAllBytes(path));
            }
            return context.Response.WriteAsync(File.ReadAllText(path));
        }

    }
}

新增WebServer类文件

using Microsoft.Owin.Hosting;
using System;

namespace ConfigTool.WebSite
{
    public class WebServer : IDisposable
    {
        IDisposable server;
        int port = 8080;
        public WebServer(int port)
        {
            this.port = port;
        }

        public void Start()
        {
            Console.WriteLine("WebServer Starting");
            var host = "*";
            var addr = $"http://{host}:{port}";
            server = WebApp.Start<Startup>(url: addr);
            Console.WriteLine($"WebServer Started @ {addr}");
        }


        public void Stop()
        {
            Console.WriteLine("WebServer Stopping");
            server.Dispose();
            Console.WriteLine("WebServer Stopped");
        }


        public void Dispose()
        {
            server?.Dispose();
        }

    }
}

修改控制台程序TestWebSite的Program.cs文件代码如下:

using ConfigTool.WebSite;
using System;

namespace ConfigTool.TestWebSite
{
    internal class Program
    {
        static void Main(string[] args)
        {
            WebServer server = new WebServer(8080);
            server.Start();

            Console.ReadLine();
        }
    }
}

修改win服务程序WinService的MainService.cs(默认Service1.cs)文件代码如下:

using ConfigTool.WebSite;
using System.Configuration;
using System.ServiceProcess;

namespace ConfigTool.WinService
{
    public partial class MainService : ServiceBase
    {
        public MainService()
        {
            InitializeComponent();
        }
        WebServer server;
        protected override void OnStart(string[] args)
        {
            var port = ConfigurationManager.AppSettings.Get("PORT");
            if (!int.TryParse(port, out int iport))
            {
                iport = 5000;
            }
            server = new WebServer(iport);
            server.Start();
        }

        protected override void OnStop()
        {
            server?.Stop();
        }
    }
}

编写服务安装卸载脚本

@echo.service installing......  
@echo off  
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe "ConfigTool.WinService.exe"
@sc config ConfigTool.WinService start= auto
@net Start ConfigTool.WinService
@echo off  
@echo.service started!  
@pause
@echo.uninstall service......  
@echo off  
@net Stop ConfigTool.WinService
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u "ConfigTool.WinService.exe"
@echo off  
@echo.service uninstalled!  
@pause

 

标签:perfix,web,ConfigTool,宿主,application,context,服务器,using,Response
From: https://www.cnblogs.com/lucienbao/p/18231467/frameworkhostedservice

相关文章

  • 服务器安装centos系统报错
    安装centos报错:dracut-initqueue:warning:dracut-initqueuetimeout-startingtimeoutscripts解决方法U盘启动报错信息 查看U盘的对应分区 重启电脑按e进入编辑模式将:vmlinuzinitrd=initrd.imginst.stage2=hd:LABEL=CentOS\x207\x20x86_64rd.live.checkquiet改......
  • UDP练习题——实现将自己加入到多播组中并等待服务器发送数据包
    设计程序,要求程序可以加入到一个多播组中并等待服务器发送,数据包,并且程序还需要具有发送功能,如果收到数据包则把消息内容输出到终端,消息内容格,式「消息来源IP消息时间1:消息内容多播地址和端口号/*************************************************************************......
  • Linux服务器磁盘清理与Inode节点清理指南
    Linux服务器磁盘清理与Inode节点清理指南在管理Linux服务器时,定期清理磁盘空间和inode节点是维护系统性能和稳定性的重要任务。磁盘空间清理可确保系统不会因为空间不足而出现问题,而inode节点清理则有助于避免系统因过多小文件而性能下降。本指南将介绍如何执行这些清理操......
  • Dynamics CRM 365 Web API 入门
    创建VisualStudio项目启动VisualStudio2022,然后选择“创建新项目”。创建新的控制台应用项目。通过设置“位置”和“项目名称”来配置项目。通过选择“.NET8.0(长期支持)”和“不使用顶级语句”来配置项目。然后单击“创建”。编辑Program.cs按照以下后续步骤为主程......
  • 基于BungeeCord搭建 多服务端 Minecraft 我的世界 Bedwars服务器 教程
    本文基于BungeeCord搭建多服务我的世界起床战争服务器本文章后续会持续更新由于多世界插件EssentialsX-Core与Bedwars1058在部分指令上有冲突,于是建议使用BungeeCord(之后我简称BC)搭建多服务端minecraft服务器,将起床Bedwars服务分离出来,顺便将其他的服务比如登陆大厅等分离出......
  • 探索sqlmap在WebSocket安全测试中的应用
    探索sqlmap在WebSocket安全测试中的应用WebSocket与HTTP的区别WebSocket,对于初次接触的人来说,往往会引发一个疑问:既然我们已经有了广泛使用的HTTP协议,为何还需要引入另一种协议?WebSocket又能为我们带来哪些实质性的好处呢?这背后的答案在于HTTP协议的一个关键限制——通信的发起......
  • Buuctf-Web(37-42)
    37[网鼎杯2020朱雀组]phpweb参考[网鼎杯2020朱雀组]phpweb1-CSDN博客[buuctf-网鼎杯2020朱雀组]phpweb(小宇特详解)_buuctf[网鼎杯2020朱雀组]phpweb-CSDN博客打开是这个界面,大概5秒刷新一次先来一遍扫目录,看源码,抓包一扫就409,应该做了限制,源码没发现什么,抓包看看......
  • Buuctf-Web(1-6)
    1[极客大挑战2019]EasySQL根据题目,用单引号检测是否存在SQL注入漏洞分析报错信息:看'单引号后面跟着的字符,是什么字符,它的闭合字符就是什么,若是没有,就为数字型。在两个位置用单引号测试,发现闭合符号为单引号,注入点在password万能密码法常规法注入流程数据库->表->字段-......
  • 适合小白学习的项目1901java体育馆管理系统Myeclipse开发mysql数据库web结构java编程
    一、源码特点java体育馆管理系统是一套完善的web设计系统,对理解JSPjava编程开发语言有帮助采用了java设计,系统具有完整的源代码和数据库,系统采用web模式,系统主要采用B/S模式开发。开发环境为TOMCAT7.0,Myeclipse8.5开发,数据库为Mysql,使用java语言开发。java体育馆管理系......
  • web前端期末大作业:美食文化网页设计与实现——美食餐厅三级(HTML+CSS+JavaScript)
    ......