asp.net web api的自托管模式HttpSelfHostServer可以以控制台程序或windows服务程序为宿主,不单单依赖于IIS web服务器
2013-10-18 09:31
1201 查看
Self-Hosting ASP.NET Web API
http://theshravan.net/self-hosting-asp-net-web-api/ 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:
[align=justify]Specify the base address for your HTTP server (using HttpSelfHostConfiguration class)[/align]
[align=justify]Configure Http routes for your web APIs[/align]
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.
[align=justify]System.Web.Http.dll[/align][align=justify]The core runtime assembly for ASP.NET Web API[/align]
[align=justify]System.Net.Http.dll[/align][align=justify]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[/align]
[align=justify]System.Net.Http.WebRequest.dll[/align][align=justify]Provides additional classes for programming HTTP applications[/align]
[align=justify]System.Web.Http.SelfHost.dll[/align][align=justify]Contains everything you need to host ASP.NET Web API within your own process (outside of IIS)[/align]
[align=justify]System.Net.Http.Formatting.dll[/align][align=justify]Adds support for formatting and content negotiation to System.Net.Http. It includes support for JSON, XML, and form URL encoded data[/align]
[align=justify]Newtonsoft.Json.dll[/align][align=justify]Dependent library for System.Net.Http.Formatting.dll to include support for JSON[/align]
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()
{
}
}
相关文章推荐
- 如何使用Apache HTTP Server?(window)
- 网络IT认证三大主流
- Qt提示 "Could not connect to AppWrapper, Please make sure TCP port 12005 is not blocked"解决方法
- Android 检测网络连接状态
- 安畅网络-上海五大数据中心一览
- 网络编程毕业生总结的上学和工作期间的一些经验教训(受益匪浅)
- 聊聊Http协议
- AFNetWorking网络库教程
- Web-Attak系列教程第二季0x12讲——HTTP的请求与响应格式
- IE8兼容<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
- HttpURLConnecttion网络图片查看器
- Backtrack5 网络漏洞攻击工具 Metasploit
- PACHE COMMON HTTPCLIENT介绍[转]
- HTTP状态码大全
- Android NFC自动连接Wifi网络进行Socket TCP通信
- 刷新电脑DNS缓存
- Java Socket PC端 服务器 TCP
- 判断ip地址的合法性,利用网络套接字相关接口
- HDU 3605 二分图的多重匹配 || 状压网络流
- 添加网络打印机方法