Use OWIN to Self-Host ASP.NET Web API 2
This tutorial shows how to host ASP.NET Web API in a console application, using OWIN to self-host the Web API framework.
Open Web Interface for .NET (OWIN) defines an abstraction between .NET web servers and web applications. OWIN decouples the web application from the server, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS.
Software versions used in the tutorial
You can find the complete source code for this tutorial at aspnet.codeplex.com.
Create a Console Application
On the File menu, click New, then click Project. From Installed Templates, under Visual C#, click Windows and then click Console Application. Name the project “OwinSelfhostSample” and click OK.

Add the Web API and OWIN Packages
From the Tools menu, click Library Package Manager, then click Package Manager Console. In the Package Manager Console window, enter the following command:
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
This will install the WebAPI OWIN selfhost package and all the required OWIN packages.

Configure Web API for Self-Host
In Solution Explorer, right click the project and select Add / Class to add a new class. Name the class Startup.

Replace all of the boilerplate code in this file with the following:
using Owin;
using System.Web.Http; namespace OwinSelfhostSample
{
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.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); appBuilder.UseWebApi(config);
}
}
}
Add a Web API Controller
Next, add a Web API controller class. In Solution Explorer, right click the project and select Add / Class to add a new class. Name the classValuesController.
Replace all of the boilerplate code in this file with the following:
using System.Collections.Generic;
using System.Web.Http; namespace OwinSelfhostSample
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} // 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)
{
}
}
}
Start the OWIN Host and Make a Request Using HttpClient
Replace all of the boilerplate code in the Program.cs file with the following:
using Microsoft.Owin.Hosting;
using System;
using System.Net.Http; namespace OwinSelfhostSample
{
public class Program
{
static void Main()
{
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/values").Result; Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
} Console.ReadLine();
}
}
}
Running the Application
To run the application, press F5 in Visual Studio. The output should look like the following:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Tue, 09 Jul 2013 18:10:15 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 19
Content-Type: application/json; charset=utf-8
}
["value1","value2"]

Additional Resources
Host ASP.NET Web API in an Azure Worker Role
This article was originally created on July 9, 2013
Author Information
Kanchan Mehrotra
Use OWIN to Self-Host ASP.NET Web API 2的更多相关文章
- 为IIS Host ASP.NET Web Api添加Owin Middleware
将OWIN App部署在IIS上 要想将Owin App部署在IIS上,只添加Package:Microsoft.OWIN.Host.SystemWeb包即可.它提供了所有Owin配置,Middlew ...
- [转] 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/ ...
- 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 ...
- ASP.NET Web API 安全筛选器
原文:https://msdn.microsoft.com/zh-cn/magazine/dn781361.aspx 身份验证和授权是应用程序安全的基础.身份验证通过验证提供的凭据来确定用户身份,而授 ...
- asp.net web api的源码
从安装的NuGet packages逆向找回去 <package id="Microsoft.AspNet.WebApi.Core" version="5.2.7& ...
- asp.net web api的自托管模式HttpSelfHostServer可以以控制台程序或windows服务程序为宿主,不单单依赖于IIS web服务器
Self-Hosting ASP.NET Web API http://theshravan.net/self-hosting-asp-net-web-api/ http://www.piotrwal ...
- 使用 OWIN 作为 ASP.NET Web API 的宿主
使用 OWIN 作为 ASP.NET Web API 的宿主 ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动 设备)的 HTTP 服务. ASP.NET ...
- 购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证
原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证 chsakell分享了前端使用AngularJS,后端使用ASP. ...
- ASP.NET Web API 框架研究 Web Host模式路由及将请求转出到消息处理管道
Web Host 模式下的路由本质上还是通过ASP.NET 路由系统来进行路由的,只是通过继承和组合的方式对ASP.NET路由系统的内部的类进行了一些封装,产生自己专用一套类结构,功能逻辑基本都是一样 ...
随机推荐
- 计算新浪Weibo消息长度
此文为计算新浪Weibo的消息长度的方法. 就是 (发言请遵守社区公约,还可以输入119字). var getMessageLength = (function() { var byteLength ...
- linux0.12 链接过程
终于编译OK了..可链接就是一大堆错误 问题1: boot/head.o: In function `startup_32': (.text+0x10): undefined reference to ...
- Storm拓扑的并行度(parallelism)介绍
Storm拓扑的并行度(parallelism)介绍 1.Storm分为3个主要实体,用于在Storm集群中运行拓扑 工作进程:Worker Process,也称为Worker ...
- JDBC远程从一个MySql数据库中的一张表里面读出数据(这个数据库需要用SSH隧道连接,大约8W条数据),然后分别插入到另一个数据库中的两张表里
package com.eeepay.lzj.db; import java.sql.Connection; import java.sql.Date; import java.sql.DriverM ...
- JS(七)
JS又上完了,还是感觉JS技巧性很强,需要多积累经验...看了一下PHP的内容,感觉搭建环境好麻烦,结果回来下了个wamp感觉好像就可以了..... 1.红绿蓝颜色条: <!DOCTYPE ht ...
- 由fprintf和printf看C语言三种标准流
一.C语言中的三种标准流 1.标准输入流:stdin 2.标准输出流:stdout 3.标准错误输出流:stderr 他们的类型都是File * 二.fprintf于printf的区别 frintf( ...
- iPhone应用程序间传递数据
前一篇简单的介绍了iPhone应用程序间通信,主要是通过在被调用应用的Info.plist中加入URL方案,在应用中通过openUrl来实现程序的调用.而应用程序间的数据传递则可以更具url来实现,例 ...
- 10个利用Eclipse调试Java的常见技巧
http://www.open-open.com/news/view/1ad9099 阅读目录 1. Conditional Breakpoint 2. Exception Breakpoint 3. ...
- Kinect for Windows V2和V1对照开发___彩色数据获取并用OpenCV2.4.10显示
V1彩色分辨率:640x480 V2彩色分辨率:1920x1080 1,打开彩色图像帧的方式 对于V1: 使用NuiImageStreamOpen方法打开 hr = m_PNuiSensor-> ...
- 设计模式17---设计模式之模板方法模式(Template Method)(行为型)
1.场景模拟 使用软件模拟登录控制,普通用户和工作人员用户,工作人员的密码在数据库中是加密的. 步骤大致如下: 前台提交,后台获取登录信息,同数据库中的登陆信息进行比较,只不过工作人员是加密的,普通用 ...