今天突然想起改良一下以前搭建的“windows service承载的web api”服务,以前也是直接引用的类库,没有使用nuget包,时隔几年应该很旧版本了吧。所以本次把需要nuget获取的包记录一下。
还有几点需要注意一下:
1、设定webapi仅仅使用json格式
using System;using System.Collections.Generic;using System.Net.Http;using System.Net.Http.Formatting;using System.Net.Http.Headers;namespace NetMiddlewareSvr{ ////// Json格式头部类 /// public class JsonContentNegotiator : IContentNegotiator { private readonly JsonMediaTypeFormatter _jsonFormatter; public JsonContentNegotiator(JsonMediaTypeFormatter formatter) { _jsonFormatter = formatter; } public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerableformatters) { var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json")); return result; } }}
2、修改默认路由规则:
using Owin;using System.Net.Http.Formatting;using System.Web.Http;namespace NetMiddlewareSvr{ public class RegisterRoutesStartup { public void Configuration(IAppBuilder appBuilder) { HttpConfiguration config = new HttpConfiguration(); //自定义路由 config.Routes.MapHttpRoute( name: "CustomApi", routeTemplate: "api/{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、启动监听
public partial class NetMiddwareService : ServiceBase { private IDisposable hostObject; public NetMiddwareService() { InitializeComponent(); } protected override void OnStart(string[] args) { hostObject = hostObject = WebApp.Start("http://" + "127.0.0.1" + ":5990"); } protected override void OnStop() { } }
补充一下nuget的顺序:Microsoft.Owin->Microsoft.Owin.Hosting->Microsoft.AspNet.WebApi.Core,剩下的是依赖包自动导入的。当然log4net和Newtonsoft.Json不是owin的依赖包