引入依赖
在通过Nuget包管理器安装如下组件
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Hosting
Microsoft.Owin.Host.HttpListener
1、创建 JsonContentNegotiator 类
class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter jsonMediaTypeFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
this.jsonMediaTypeFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(this.jsonMediaTypeFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
2、创建 RegisterRoutesStartup 类
class RegisterRoutesStartup
{
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
//自定义路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "socketApi/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//只响应Json请求
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
appBuilder.UseWebApi(config);
}
}
3、在服务(Service1)中启动WebApi
public partial class Service1 : ServiceBase
{
private string hostSocket;
private IDisposable hostObject;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
hostSocket = Const.GetIpAddress();
hostObject = WebApp.Start<RegisterRoutesStartup>("http://" + hostSocket + ":" + Const.GetAppSetting("portObject"));
}
protected override void OnStop()
{
hostObject.Dispose();
}
}
4、创建 Const 类
public class Const
{
public static string GetAppSetting(string key)
{
foreach(string item in ConfigurationManager.AppSettings)
{
if(key == item)
{
return ConfigurationManager.AppSettings[item];
}
}
return "";
}
public static string GetIpAddress()
{
string ip = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
if ("127.0.0.1" == _IPAddress.ToString())
{
continue;
}
else
{
ip = _IPAddress.ToString();
break;
}
}
}
return ip;
}
}
5、最后创建 WebApi 类
public class DemoController : ApiController
{
/// <summary>
/// 访问 http://host:port/socketApi/Demo/Test
/// </summary>
/// <returns></returns>
[HttpGet]
public string Test()
{
return "Are you ok?";
}
}