WebAPI-寄宿方式启动

1.首先创建一个类库,用于创建模型 Contact

using System;

namespace Common
{
public class Contact
{
public string Id { get; set; }
public string Name { get; set; }
public string PhoneNo { get; set; }
public string EmailAddress { get; set; }
public string Address { get; set; }
}
}

2.创建一个名为WebApi类库,用于创建原始的WebApi控制器

using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading;
using System.Web.Http;    //引用D:Program FilesMicrosoft ASP.NETASP.NET Web Stack 5PackagesMicrosoft.AspNet.WebApi.Core.5.2.3lib et45System.Web.Http.dll
using Common;

namespace WebApi
{
public class ContactsController:ApiController
{
static List<Contact> contacts;
static int counter=2;
static ContactsController()
{
contacts = new List<Contact> {
new Contact{ Id="001",Name="张三",PhoneNo="0521-12334434",EmailAddress="zhangsan@123.com",Address="江苏盐城市329号"},
new Contact{ Id="002",Name="李四",PhoneNo="0521-12324335",EmailAddress="lisi@123.com",Address="江苏南京广州路300号"}
};
}
public IEnumerable<Contact> Get(string id = null)
{
return contacts.Where(c => c.Id == id || string.IsNullOrEmpty(id));
}
public void Post(Contact contact)
{
Interlocked.Increment(ref counter);
contact.Id = counter.ToString("D3");
contacts.Add(contact);
}
public void Put(Contact contact)
{
contacts.Remove(contacts.First(c => c.Id == contact.Id));
contacts.Add(contact);
}
public void Delete(string id)
{
contacts.Remove(contacts.First(c=>c.Id==id));
}

}
}

3.创建一个控制台程序SelfHost

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Web.Http; 

//引用D:Program FilesMicrosoft ASP.NETASP.NET Web Stack 5PackagesMicrosoft.AspNet.WebApi.Core.5.2.3lib et45System.Web.Http.dll
using System.Web.Http.SelfHost;

//引用 D:Program FilesMicrosoft ASP.NETASP.NET Web Stack 5PackagesMicrosoft.AspNet.WebApi.SelfHost.5.2.3lib et45System.Web.Http.SelfHost.dll
using System.Net.Http.Formatting;

//D:Program FilesMicrosoft ASP.NETASP.NET Web Stack 5PackagesMicrosoft.AspNet.WebApi.Client.5.2.3lib et45System.Net.Http.Formatting.dll
namespace SelfHost
{
class Program
{
static void Main(string[] args)
{
Assembly.Load("WebApi,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null");  //载入WebApi.dll
HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost/selfhost");
using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
{
httpServer.Configuration.Routes.MapHttpRoute(
name:"DefaultApi",
routeTemplate:"api/{controller}/{id}",
defaults: new { id=RouteParameter.Optional}
);
httpServer.OpenAsync().Wait();
Console.Read();
}
}
}
}

原文地址:https://www.cnblogs.com/sundh1981/p/13903053.html