过去做 端游的Http 服务器 用的WebApi 或者Mvc架构,都是放在iis。。。而我已经是懒出一个地步,并不想去配iis,或者去管理iis,所以我很喜欢 Self host 的启动方式。

C#做 http 有2个轻量级的框架, 一个是Nancy ,一个是 微软官方的Web Api 都可以通过owin self host 在应用程序中启动监听

Web Api

官方教程 :https://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api

新建一个控制台从程序 
在Nuget控制台上 安装包 Install-Package Microsoft.AspNet.WebApi.OwinSelfHost 
然后添加一个Owin Startup类 
以往所有的配置都正常的放在Startup中进行配置就可以

public 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.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

然后在Main 函数里面加入 WebApp.Start() 就会在SelfHost 上面运行你的Web Api,十分简洁

class Program
{
static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response =client.GetAsync(baseAddress + "api/home").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
Console.ReadLine();
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

尝试添加一个Controller

public class HomeController : ApiController
{
// GET api/values
public IHttpActionResult Get()
{
return Ok(125);
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

尝试运行的结果 

Nancy

Nancy是很多人都推荐的一个轻量级的Http 库,可以架在Mono,.net.core 上,也是开源 
安装Nancy可以 Install-Package Nancy 
而要 在SelfHost 监听则需要安装以下3个

Install-Package Microsoft.Owin.Hosting
Install-Package Microsoft.Owin.Host.HttpListener
Install-Package Nancy.Owin
  • 1
  • 2
  • 3

在OwinStartup中表明使用Nancy

using Owin;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseNancy();
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

入口也是通过WebApp.Start(url)

using Microsoft.Owin.Hosting;
class Program
{
static void Main(string[] args)
{
var url = "http://+:8080";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine("Running on {0}", url);
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

来源: https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-owin#katana—httplistener-selfhost 
添加一个Module

/// <summary>
/// 发现
/// 可以通过 Before 进行 安全的验证
/// </summary>
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/"] = x => "Hello";
Get["/login"] = x => { return "person name :" + Request.Query.name + " age : " + Request.Query.age; };
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

运行结果 
 

用Web api /Nancy 通过Owin Self Host简易实现一个 Http 服务器的更多相关文章

  1. 购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证

    原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证 chsakell分享了前端使用AngularJS,后端使用ASP. ...

  2. [转] JSON Web Token in ASP.NET Web API 2 using Owin

    本文转自:http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/ ...

  3. JSON Web Token in ASP.NET Web API 2 using Owin

    In the previous post Decouple OWIN Authorization Server from Resource Server we saw how we can separ ...

  4. ASP.NET Web API消息处理管道:Self Host下的消息处理管道[下篇]

    ASP.NET Web API消息处理管道:Self Host下的消息处理管道[下篇] 我们知道ASP.NET Web API借助于HttpSelfHostServer以Self Host模式寄宿于当 ...

  5. ASP.NET Web API的消息处理管道: Self Host下的消息处理管道[上篇]

    ASP.NET Web API的消息处理管道: Self Host下的消息处理管道[上篇] ASP.NET Web API服务端框架核心是一个独立于具体寄宿环境的消息处理管道,它不关心请求消息来源于何 ...

  6. ASP.NET Web API实践系列02,在MVC4下的一个实例, 包含EF Code First,依赖注入, Bootstrap等

    本篇体验在MVC4下,实现一个对Book信息的管理,包括增删查等,用到了EF Code First, 使用Unity进行依赖注入,前端使用Bootstrap美化.先上最终效果: →创建一个MVC4项目 ...

  7. ASP.NET Web API 记录请求响应数据到日志的一个方法

    原文:http://blog.bossma.cn/dotnet/asp-net-web-api-log-request-response/ ASP.NET Web API 记录请求响应数据到日志的一个 ...

  8. OAuth Implementation for ASP.NET Web API using Microsoft Owin.

    http://blog.geveo.com/OAuth-Implementation-for-WebAPI2 OAuth is an open standard for token based aut ...

  9. 使用JS通过Web API执行批量操作,多个操作是一个事务!

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复235或者20161105可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...

随机推荐

  1. iptables防火墙端口操作

    1.将开放的端口写入iptables中,在终端中输入命令: /sbin/iptables -I INPUT -p tcp --dport -j ACCEPT 2.保存上一步的修改内容,输入命令: /e ...

  2. CodeForces 937C Save Energy! 水题

    题意: 一个炉子烤鸡,炉子打开的时候一共$T$分钟可以烤完,关闭的时候一共$2T$分钟可以烤完,炉子每$K$分钟自动关闭,厨师每$D$分钟回来检查,打开炉子 问多长时间烤完.. 题解: 用整数写比较稳 ...

  3. 毫秒倒计时小Demo

    Demo截图: Demo:Demo 上代码: <!DOCTYPE html> <html lang="en"> <head> <meta ...

  4. 将C注册到lua环境中使用

    注册到lua的方式有两种,一种是lua解释器,如果支持动态链接,使用动态链接机制,将函数接口编译成动态链接库,然后将动态链接库放到lua的C路径(LUA_CPATH)中,然后在lua文件中直接使用 r ...

  5. python操作三大主流数据库(13)python操作redis之新闻项目实战①新闻数据的导入

    1.新闻处理页面redis_news.py #coding:utf-8 import math import redis class RedisNews(object): def __init__(s ...

  6. 使用tomcat发布含有shtml文件的web程序

    平常都是使用html或jsp,当导入含有shtml的一个web项目时,向平常一样使用Jetty运行,访问到shtml文件时,直接在浏览器上显示出了源码. 查询,使用tomcat发布,修改tomcat的 ...

  7. Java中instanceof与getClass的区别

    在比较一个类和另一个类是否属于同一个类实例的时候,通常可以采用instanceof和getClass两种方法比较两者是否相等来判断,但是两者在判断上面是有差别的,下面通过代码说明: public cl ...

  8. 解决:angularjs radio默认选中失效问题

    添加ng-model后checked="checked"失效,可见angularjs也不好,会失效html标准属性   解决:添加ng-checked="1" ...

  9. tornado的异步效果

    第一种方式: import tornado.ioloop import tornado.web from tornado import gen from tornado.concurrent impo ...

  10. swift 实践- 01 -- UItableView的简单使用

    import UIKit class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{ over ...