http://www.piotrwalat.net/hosting-web-api-in-windows-service/

ASP.NET Web API is a framework for building HTTP services that can reach a broad range of clients including browsers, phones and tablets. ASP.NET Web API ships with ASP.NET MVC 4 and is part of the Microsoft web platform.

You can read more about Web API in my earlier article @ http://theshravan.net/say-hello-to-asp-net-web-api/

As I mentioned earlier ASP.NET Web API ships with ASP.NET MVC 4. But we are not limited to hosting Web APIs in IIS. ASP.NET Web API gives you the flexibility to host your Web APIs anywhere you would like, including self-hosting in our own process (e.g.: Wpf Application , Console Application, etc…).

In this article I am going explain how to Self-Host Web API in a Console Application and consume from a client application. Same code we can use for Self-Host Web API  in any our own process (any application).

To self-host a Web API first we need to setup server configuration, Here are the steps for server configuration:

    1. Specify the base address for your HTTP server (using HttpSelfHostConfiguration class)
    2. Configure Http routes for your web APIs

Configuring routes is same as using ASP.NET Routing, But only thing is the routes need to be added to the route collection on ourHttpSelfHostConfiguration instance created in first step.

I am creating a Console Application using Visual Studio. Let’s have a look at project structure in solution explorer.

This is plain vanilla Console Application , We need  following important assemblies to work with Web API.

  • System.Web.Http.dll
    • The core runtime assembly for ASP.NET Web API
  • System.Net.Http.dll
    • Provides a programming interface for modern HTTP applications. This includes HttpClient for sending requests over HTTP, as well as HttpRequestMessage and HttpResponseMessage for processing HTTP messages
  • System.Net.Http.WebRequest.dll
    • Provides additional classes for programming HTTP applications
  • System.Web.Http.SelfHost.dll
    • Contains everything you need to host ASP.NET Web API within your own process (outside of IIS)
  • System.Net.Http.Formatting.dll
    • Adds support for formatting and content negotiation to System.Net.Http. It includes support for JSON, XML, and form URL encoded data
  • Newtonsoft.Json.dll
    • Dependent library for System.Net.Http.Formatting.dll to include support for JSON

I grabbed all the above assemblies & add to my project using nuget.

I am creating my Web API controller under Api folder in project (you can place it any where in the project).

using System.Web.Http;  namespace WebAPISelfHostSample.Api {     public class HelloWorldController : ApiController     {         public string Get()         {             return "Hi!, Self-Hosted Web Api Application Get()";         }          public string Get(int id)         {             return "Hi!, Self-Hosted Web Api Application Get() With Id: " + id;         }     } }

Let’s write code in  Program .cs for creating Self-Hosting Web API.

using System; using System.Web.Http; using System.Web.Http.SelfHost;  namespace WebAPISelfHostSample {     class Program     {         static void Main(string[] args)         {             var baseAddress = "http://localhost:8080/";             var config = new HttpSelfHostConfiguration(baseAddress);              config.Routes.MapHttpRoute(                                 name : "DefaultApi",                                 routeTemplate : "api/{controller}/{id}",                                 defaults : new { id = RouteParameter.Optional });              Console.WriteLine("Instantiating The Server...");             using (var server = new HttpSelfHostServer(config))             {                    server.OpenAsync().Wait();                 Console.WriteLine("Server is Running Now... @ " + baseAddress);                 Console.ReadLine();             }         }     } }

Now Build & Run the Application (Hit F5 – Make sure Visual Studio is running under Administrator , other we will get an exception).

We are Successfully Self-Hosted the  Hello World Web Api & The Server is up & running now.

Let’s create client to test this, here is the client code:

using System; using System.Net.Http;  namespace SelfHostWebApiClient {     class Program     {         static void Main(string[] args)         {             var baseAddress = "http://localhost:8080/";              var client = new HttpClient { BaseAddress = new Uri(baseAddress) };              Console.WriteLine("Client received: {0}", client.GetStringAsync("api/helloworld").Result);             Console.WriteLine("Client received: {0}", client.GetStringAsync("api/helloworld/10").Result);              Console.ReadLine();         }     } }

Result:

We are successfully able to access Self-Hosted Web Api from our client application. We can Self Host any complex Web API.

--------------------------------寄宿windowns 服务------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Reflection;
using System.IO;

using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.SelfHost;

namespace WebAPISelfHost
{
public partial class Service1 : ServiceBase
{
static HttpSelfHostServer CreateHost(string address)
{
// Create normal config
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address);

config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Home", id = RouteParameter.Optional });

HttpSelfHostServer server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();

return server;
}

public Service1()
{
InitializeComponent();

}

protected override void OnStart(string[] args)
{
HttpSelfHostServer server = CreateHost("http://localhost:8080");
}

protected override void OnStop()
{
}
}

asp.net web api的自托管模式HttpSelfHostServer可以以控制台程序或windows服务程序为宿主,不单单依赖于IIS web服务器的更多相关文章

  1. C#开发微信门户及应用(47) - 整合Web API、微信后台管理及前端微信小程序的应用方案

    在微信开发中,我一直强调需要建立一个比较统一的Web API接口体系,以便实现数据的集中化,这样我们在常规的Web业务系统,Winform业务系统.微信应用.微信小程序.APP等方面,都可以直接调用基 ...

  2. ASP.NET WEB API的服务托管(Self-HOST)

    如果我们想对外发布RESTful API,可以基于ASP.NET来构建Restful APIs,但需要部署IIS吗?答案是不必.你可以把它托管到一个Windows Service.具体如何把WEB A ...

  3. 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【四】——实现模型工厂,依赖注入以及格式配置

    系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 前言 在上一篇中,我们已经初步开始使用Web Api了,但同时出现了一些很多不足之处,本章我们就着 ...

  4. 集成架构:对比 Web API 与面向服务的架构和企业应用程序集成(转)

    http://kb.cnblogs.com/page/521644/ 摘要:总体上讲,SOA 和 Web API 似乎解决的是同一个问题:以实时的.可重用的方式公开业务功能.本教程将分析这些举措有何不 ...

  5. (转)集成架构:对比 Web API 与面向服务的架构和企业应用程序集成

    摘要:总体上讲,SOA 和 Web API 似乎解决的是同一个问题:以实时的.可重用的方式公开业务功能.本教程将分析这些举措有何不同,以及如何将它们融入到一个不断演变的集成架构中.文中还将讨论 API ...

  6. .NET 跨平台RPC框架DotNettyRPC Web后台快速开发框架(.NET Core) EasyWcf------无需配置,无需引用,动态绑定,轻松使用 C# .NET 0配置使用Wcf(半成品) C# .NET Socket 简单实用框架 C# .NET 0命令行安装Windows服务程序

    .NET 跨平台RPC框架DotNettyRPC   DotNettyRPC 1.简介 DotNettyRPC是一个基于DotNetty的跨平台RPC框架,支持.NET45以及.NET Standar ...

  7. Self Host模式下的ASP. NET Web API是如何进行请求的监听与处理的?

    构成ASP.NET Web API核心框架的消息处理管道既不关心请求消息来源于何处,也不需要考虑响应消息归于何方.当我们采用Web Host模式将一个ASP.NET应用作为目标Web API的宿主时, ...

  8. ASP.NET Web API 框架研究 Web Host模式路由及将请求转出到消息处理管道

    Web Host 模式下的路由本质上还是通过ASP.NET 路由系统来进行路由的,只是通过继承和组合的方式对ASP.NET路由系统的内部的类进行了一些封装,产生自己专用一套类结构,功能逻辑基本都是一样 ...

  9. 2.3属性在 ASP.NET Web API 2 路由

    路由是 Web API 如何匹配 URI 的行动.Web API 2 支持一种新型的路由,称为属性路由.顾名思义,属性路由使用属性来定义路由.属性路由给你更多的控制 Uri 在您的 web API.例 ...

随机推荐

  1. 数据挖掘经典算法之KNN

    KNN也称为k近邻算法,本质思想:物以类聚. 在分类或者预测中,待分类或预测的样本的类别和走势将直接参考与该样本最“近邻”的k个邻居. 在这种思路下,KNN注定会遇到3个问题: (1): 谁是我的邻居 ...

  2. OpenWrt for vmware 从openwrt.org下载10.03.1 或是自己下载最新的源码进行编译生成x86 vmdk格式

    1,直接从OpenWrt.org官网下载 http://downloads.openwrt.org/backfire/10.03.1/x86_generic/ 更新OpenWrt在线软件源 opkg ...

  3. 【水题递归】【HDU2044】我大沙茶了

    有一只经过训练的蜜蜂只能爬向右侧相邻的蜂房,不能反向爬行.请编程计算蜜蜂从蜂房a爬到蜂房b的可能路线数. 其中,蜂房的结构如下所示.   Input 输入数据的第一行是一个整数N,表示测试实例的个数, ...

  4. What should we do when meet a crash in android?

    制造一个crash   为了演示的目的,我在libsensors的open_sensors_device中故意制造了一个crash:   static int open_sensors_device( ...

  5. PHP常用内置函数

    $_SERVER['SCRIPT_NAME'] 返回/mantis/test.php 相对路径 __FILE__返回文件的绝对路径 $_SERVER['HTTP_X_FORWARDED_PROTO'] ...

  6. WIN7 Net Configuration Assistant打不开

     转自  http://www.cnblogs.com/caojie0432/archive/2013/07/30/3225230.html  作者:db_suploc 今天在安装oracle10g的 ...

  7. android 补间动画

    android开发过程中,为了更好的展示应用程序,应用程序添加动画,能够很好地实现这个功能.如果动画中的图像变化有一定的规律,可以采用自动生成图像的方式来生成动画,例如图像的移动.旋转.缩放等.自动生 ...

  8. [转载]android中The connection to adb is down,问题和解决

    原网址:http://blog.sina.com.cn/s/blog_5fc93373010164p3.html 今天我出现了第3个错误,于是百度了一下.感觉这篇博客对我挺有帮助,推荐给大家.以下是原 ...

  9. java学习——函数

    class FunctionDemo { public static void main(String[] args) { System.out.println("Hello World!& ...

  10. Json.Net介绍及实例

    本系列教程假设读者已经对Json有一定的了解,关于Json在这里不多说.本系列教程希望能对读者开发涉及到Json的.Net项目有一定的帮助.本系列教程是根据官方文档资料和自己项目应用汇总而成.如果觉得 ...