界面:

结构:

一、新建winform工程

NuGet安装以下几个包:

(1):Microsoft.AspNet.WebApi.OwinSelfHost

(2):Microsoft.AspNet.SignalR

(3)静态文件处理的中间件:Beginor.Owin.StaticFile

(4)Microsoft.Owin.Cors

(5) 将其他dll打包成一个exe:Costura.Fody

 二、代码

启动类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using OwinTest2.model;
using OwinTest2.view;namespace OwinTest2
{static class Program{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(GlobalData.GetForm1());}}
}

Form1 类:

using System;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Owin.Hosting;
using OwinTest2.server;
using OwinTest2.model;namespace OwinTest2.view
{public partial class Form1 : Form{//Owin服务实例对象private IDisposable disposeable;public Form1(){InitializeComponent();Init();}private void Init(){//非主线程亦可操作界面CheckForIllegalCrossThreadCalls = false;log_textBox.Text = "日志:\r\n";SetLog("开始获取本机IP...");//获取本机IPIPHostEntry here = Dns.GetHostEntry(Dns.GetHostName());foreach (IPAddress _ip in here.AddressList){if (_ip.AddressFamily.ToString().ToUpper() == "INTERNETWORK"){GlobalData.ServerIp = _ip.ToString();//GlobalData.Port = (9000 + new Random().Next(1000)).ToString();new Thread(() =>{//本地Http服务器string baseAddress = "http://" + GlobalData.ServerIp + ":" + GlobalData.Port;disposeable = WebApp.Start<Startup>(url: baseAddress);}){ Name = "获取日志线程" }.Start();break;}}this.Text = this.Text + "  " + GlobalData.ServerIp + ":" + GlobalData.Port;SetLog("本机IP端口:" + GlobalData.ServerIp + ":" + GlobalData.Port);}public void SetLog(string log){log_textBox.AppendText(log + "\r\n");}private void Form1_FormClosing(object sender, FormClosingEventArgs e){DialogResult result = MessageBox.Show("确认退出吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);if (result == DialogResult.OK){disposeable.Dispose();//Dispose();//Application.Exit();System.Environment.Exit(0);}else{e.Cancel = true;}}}
}

Startup 配置类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Beginor.Owin.StaticFile;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;[assembly: OwinStartup(typeof(OwinTest2.server.Startup))]
namespace OwinTest2.server
{class Startup{// This code configures Web API. The Startup class is specified as a type// parameter in the WebApp.Start method.public void Configuration(IAppBuilder appBuilder){// Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}", //{action}目的是为了一个Controller能有多个Get Post方法defaults: new { id = RouteParameter.Optional });config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));appBuilder.UseWebApi(config);//静态文件托管appBuilder.Map("/page", map =>{// 允许跨域map.UseCors(CorsOptions.AllowAll);map.UseStaticFile(new StaticFileMiddlewareOptions{RootDirectory = @"../Debug/page",DefaultFile = "page/index.html",EnableETag = true,EnableHtml5LocationMode = true,MimeTypeProvider = new MimeTypeProvider(new Dictionary<string, string>{{ ".html", "text/html" },{ ".htm", "text/html" },{ ".dtd", "text/xml" },{ ".xml", "text/xml" },{ ".ico", "image/x-icon" },{ ".css", "text/css" },{ ".js", "application/javascript" },{ ".json", "application/json" },{ ".jpg", "image/jpeg" },{ ".png", "image/png" },{ ".gif", "image/gif" },{ ".config", "text/xml" },{ ".woff2", "application/font-woff2"},{ ".eot", "application/vnd.ms-fontobject" },{ ".svg", "image/svg+xml" },{ ".woff", "font/x-woff" },{ ".txt", "text/plain" },{ ".log", "text/plain" }})});});//SignalR托管appBuilder.Map("/signalr", map =>{// 允许跨域map.UseCors(CorsOptions.AllowAll);var hubConfiguration = new HubConfiguration{//Resolver = **,// You can enable JSONP by uncommenting line below.// JSONP requests are insecure but some older browsers (and some// versions of IE) require JSONP to work cross domainEnableJSONP = true,EnableDetailedErrors = true};// Run the SignalR pipeline. We‘re not using MapSignalR// since this branch is already runs under the "/signalr"// path.map.RunSignalR(hubConfiguration);});//该值表示连接在超时之前保持打开状态的时间长度。//默认为110秒//GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(110);//该值表示在连接停止之后引发断开连接事件之前要等待的时间长度。//默认为30秒GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(60);}}
}

LoginController 控制类(可用来处理异步请求):

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;namespace OwinTest2.controllers
{public class LoginController:ApiController{[HttpPost]public HttpResponseMessage login([FromBody]Obj obj){StringBuilder msg = new StringBuilder();if (obj == null){msg.Append("参数不能为空");}else{if (string.IsNullOrEmpty(obj.u_id)){msg.Append("u_id不能为空");}if (string.IsNullOrEmpty(obj.u_pwd)){msg.Append("u_pwd不能为空");}}if (msg.Length > 0){msg.Insert(0, "error:");return new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent(msg.ToString(), System.Text.Encoding.UTF8)};}//GlobalData.GetForm1().SetLog(obj.u_id + "----" + obj.u_pwd);//HttpResponseMessage result = null;//msg.Append("账号:" + obj.u_id + " 密码:" + obj.u_pwd);//result = new HttpResponseMessage(HttpStatusCode.OK)//{//    Content = new StringContent(msg.ToString(), System.Text.Encoding.UTF8)//};//return result;var httpResponseMessage = new HttpResponseMessage();//设置Cookievar cookie = new CookieHeaderValue("u_id", obj.u_id);cookie.Expires = DateTimeOffset.Now.AddDays(1);cookie.Domain = Request.RequestUri.Host;cookie.Path = "/";httpResponseMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie });//返回index.html页面httpResponseMessage.Content = new StringContent(File.ReadAllText(@".\page\index.html"), Encoding.UTF8);//指定返回什么类型的数据httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");return httpResponseMessage;}public class Obj{public string u_id { get; set; }public string u_pwd { get; set; }}}
}

主要代码都在上面了,其他没放出来的无关紧要

访问地址:http://172.20.10.7:9000/page

客户端连接SignalR地址:http://172.20.10.7:9000/signalr

172.20.10.7这个ip根据你设置的来

C# Owin快速搭建网站(免IIS),一个.exe文件即是一个服务器相关推荐

  1. 宝塔绑定域名访问不了_千字长文教你使用 宝塔面板 快速搭建网站

    本文将教大家使用 宝塔面板 快速搭建网站,云服务器购买 以及 域名注册 部分请自行上网搜索了解,亦可留言联系小编进行咨询.如果是和下方一样本地搭建演示的话,则不需要付费购买域名和主机.宝塔面板 的是 ...

  2. linux 快速建网站,如何快速建站,新手快速搭建网站教程

    越来越多的人选择个人建站,个人站长虽然门槛很低,但是有些朋友觉得Linux服务器各种复杂的命令脚本让自己没法搭建环境.今天就给大家推荐一款使用方便.功能强大的快速建站工具--云帮手,支持 Linux ...

  3. 腾讯云轻量级服务器怎么搭建网站,腾讯云轻量应用服务器新手教程:快速搭建网站...

    原标题:腾讯云轻量应用服务器新手教程:快速搭建网站 腾讯云轻量应用服务器(Lighthouse)具备轻运维.开箱即用的特点,适用于小型网站.博客.论坛.电商以及云端开发测试和学习环境等轻量级业务场景, ...

  4. jeesite如何配置swagger_用JeeSite快速搭建网站(3):提供api接口给移动端

    上次在用JeeSite快速搭建网站(2):单表的增删改查中我们实现单表数据的增删改查了,现在终于来冲击最终目标--提供api接口给移动端. 准备工作:安装swagger 以前的工作流是 服务端写好接口 ...

  5. 新手宝塔搭建网站,快速搭建网站的方法

    如何使用宝塔快速搭建网站? 1.登录自己的宝塔ID 点网站,添加站点 2.让服务器绑定你的网域 这里让服务器绑定你的域名,宝塔面板会为你自动为该域名来添加文件夹,你以后要写的网页代码都会在www/ww ...

  6. 2020年中小企业如何快速搭建网站?

    2020年中小企业如何快速搭建网站? 网站,作为互联网时代企业的一张名片,得到越来越多人的认可与重视. 企业网站不仅承担着企业品牌宣传重要的窗口角色,而且也具备开拓渠道.联络客户.服务客户的重要功能. ...

  7. 使用ThinkPHP框架快速搭建网站【转】

    原文地址:http://blog.csdn.net/ruby97/article/details/7574851 使用ThinkPHP框架快速搭建网站 这一周一直忙于做实验室的网站,基本功能算是完成了 ...

  8. 黑科技!无需代码快速搭建网站的平台来了

    通过智能网站搭建平台,可以无需代码快速搭建网站. 步骤一:注册/登陆爱用建站平台PC或移动端登陆用户中心-爱用智能网站,新用户注册[iYong通行证]. 步骤二:通过类似PPT编辑操作的可视化设计器设 ...

  9. 是否可以在另一个CSS文件中包含一个?

    是否可以在另一个CSS文件中包含一个? #1楼 是的,可以使用@import并提供css文件的路径,例如 @import url("mycssfile.css"); 要么 @imp ...

最新文章

  1. UVA - 11478 Halum 二分+差分约束
  2. python opencv SIFT,获取特征点的坐标位置
  3. mysql索引 物理文件_MySQL架构和MySQL索引
  4. jquery 过滤html代码,jquery – 如何使指令使用过滤的HTML属性?
  5. .NET的一点历史故事:擦肩而过的机遇
  6. LeetCode 1144. 递减元素使数组呈锯齿状(奇偶分别遍历)
  7. 带你玩转七牛云存储——高级篇
  8. 【布莱克智讯之声公众号】 精彩图文分类导航
  9. 人工智能+人=强大的网络安全
  10. 1分钟实现Autodesk Vault登录对话框
  11. 如何做软件需求分析(个人工作经验总结)
  12. ISP 和摄像头基本知识
  13. mac unity3D汉化包
  14. 使用GreenSock插件轻松制作精美的Web动画
  15. 按键精灵定位坐标循环_按键精灵的控制命令居然恐怖到了这种程度
  16. 家具从设计到生产一步完成 有屋拆单 SU草图拆单 全屋定制拆单 衣柜橱柜拆单 办公家具设计拆单 展柜定制拆单 宠物家具定制设计拆单软件 有屋软件
  17. 闲置台式机+文件服务器,闲置主机秒变家用NAS,让你的闲置电脑变存储中心
  18. KISS保持简单:纪念丹尼斯·里奇
  19. 怎样自学python_怎样自学Python?
  20. 在Windows服务器安装禅道

热门文章

  1. newbee-mall开源商城:秒杀功能、优惠券、对接支付宝
  2. 个人信息非法流出助长电信网络犯罪
  3. Https中间人攻击
  4. absolute+transform垂直居中失效
  5. 计算机电源多低无法使用吗,电脑电源供电不足会怎么样 电脑电源供电不足坏处介绍【详解】...
  6. 以最好,至最爱!2019广汽传祺济南明沛店GM8大客户交车啦!
  7. openfire error code=406 type=MODIFY 发文件
  8. 国寿养老暑期实习二面
  9. 《炬丰科技-半导体工艺》不同电解质对多孔氮化镓的影响
  10. 使用uni-app实现底部tabber以及切换