新建Web API工程
选Empty,勾选Web API,不要选择Web API,那样会把MVC勾上,这里不需要MVC
Web API工程属性
XML文件用于生成在线文档
新建windows服务作为Web API的宿主
WebAPIHost工程属性
控制台应用程序方便调试
windows服务安装Microsoft.AspNet.WebAPI.OwinSelfHost
工程WebAPIDemo需要引用Microsoft.Owin.dll
WebAPIDemo安装Swashbuckle
应用程序入口
using System; System.Collections.Generic; System.Diagnostics; System.linq; System.ServiceProcess; System.Text; System.Threading.Tasks;namespace WebAPIHost{ static class Program { /// <summary> /// 应用程序的主入口点。 </summary> voID Main(string[] args) { RunDeBUG(); StartService(); } private voID StartService() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { WebAPIHostService() }; ServiceBase.Run(ServicesToRun); } [Conditional("DEBUG")] RunDeBUG() { WebAPIHostService().Start(); Console.Writeline(启动成功); Console.Readline(); } }}VIEw Code
启动Web API服务
Microsoft.Owin.Hosting; System.ComponentModel; System.Configuration; System.Data; System.Threading; System.Threading.Tasks; Utils;public partial WebAPIHostService : ServiceBase { #region 构造函数 public WebAPIHostService() { InitializeComponent(); } #endregion #region OnStart 启动服务 protected overrIDe voID OnStart([] args) { int port = int.Parse(ConfigurationManager.AppSettings[WebAPIServicePort]); Startoptions options = Startoptions(); options.Urls.Add(http://127.0.0.1:" + port); options.Urls.Add(http://localhost:http://+: port); WebApp.Start<Startup>(options); LogUtil.Log(Web API 服务 启动成功); } #region OnStop 停止服务 OnStop() { LogUtil.Log(Web API 服务 停止成功); Thread.Sleep(100); //等待一会,待日志写入文件 } #region Start 启动服务 Start() { OnStart(null#endregion }}VIEw Code
配置Web API路由、拦截器以及初始化Swagger在线文档
Owin; WebAPIDemo; System.Web.http; Startup { Configuration(IAppBuilder appBuilder) { httpConfiguration config = httpConfiguration(); config.MaphttpAttributeRoutes(); config.Routes.MaphttpRoute( name: DefaultAPI,routeTemplate: API/{controller}/{ID}new { ID = RouteParameter.Optional } ); config.Filters.Add( MyExceptionFilter()); config.Filters.Add( MyActionFilter()); SwaggerConfig.Register(config); appBuilder.UseWebAPI(config); } }}VIEw Code
接口实现
1、继承APIController
2、RoutePrefix设置路由前缀
3、SwaggerResponse用于生成在线文档描述
Models; Swashbuckle.Swagger.Annotations; System.ComponentModel.DataAnnotations; System.Net; System.Net.http; System.Web.http; WebAPIDemo.Controllers{ <summary> 测试接口 </summary> [RoutePrefix(API/test)] TestController : APIController { #region TestGet 测试GET请求 测试GET请求 </summary> <param name="val">测试参数</param> [httpGet] [Route(TestGet)] [SwaggerResponse(httpStatusCode.OK,返回JsON",typeof(JsonListResult<TestGetResult>))] public httpResponseMessage TestGet( val) { List<TestGetResult> List = new List<TestGetResult>(); for (int i = 1; i <= 10; i++) { TestGetResult item = TestGetResult(); item.testValue1 = i.ToString(); item.testValue2 = i; item.testValue3 = 这是传入参数: val; List.Add(item); } var JsonResult = new JsonListResult<TestGetResult>(List,List.Count); return APIHelper.ToJson(JsonResult); } #region TestPost 测试POST请求 测试POST请求 <param name="data">POST数据 [httpPost] [Route(TestPosttypeof(JsonResult<CommonsubmitResult> httpResponseMessage TestPost([FromBody] TestPostData data) { JsonResult JsonResult = ; if (data == null) return APIHelper.ToJson(new JsonResult(请检查参数格式string msg = *** 作成功,这是您传入的参数: data.testArg; JsonResult = new JsonResult<CommonsubmitResult>( CommonsubmitResult() { msg = msg,ID = 1 }); } #region 数据类 TestGet接口返回结果 </summary> TestGetResult { 测试数据1 string testValue1 { get; set; } 测试数据2 int testValue2 { 测试数据3 string testValue3 { ; } } TestPost接口参数 </summary> [MyValIDate] TestPostData { 测试参数1 [required] string testArg { 测试日期参数 [required] [DateTime(Format = yyyyMMddHHmmssstring testTime { TestPost接口返回结果 TestPostResult { ; } } }VIEw Code
MyValIDate属性表示该数据需要校验
required必填校验
DateTime日期输入格式校验
辅助类APIHelper.cs
Newtonsoft.Json; System.Web; Utils{ APIHelper { static httpResponseMessage ToJson(object obj) { string str = JsonConvert.SerializeObject(obj); httpResponseMessage result = new httpResponseMessage { Content = new StringContent(str,EnCoding.UTF8,application/Json) }; result; } }}VIEw Code
辅助类ServiceHelper.cs
System.Collections.Concurrent; Utils{ 服务帮助类 ServiceHelper { static ConcurrentDictionary<Type,1)">object> _dict = new ConcurrentDictionary<Type,1)">object>(); 获取对象 static T Get<T>() where T : () { Type type = typeof(T); object obj = _dict.GetorAdd(type,(key) => T()); (T)obj; } static T Get<T>(Func<T> func) func()); (T)obj; } }}VIEw Code
JsonResult类
Models{ Json返回 JsonResult { 接口是否成功 virtual bool success { 结果编码 virtual ResultCode resultCode { 接口错误信息 string errorMsg { 记录总数(可空类型) int? total { 默认构造函数 JsonResult() { } 接口失败返回数据 public JsonResult( errorMsg,ResultCode resultCode) { this.success = false; this.resultCode = resultCode; this.errorMsg = errorMsg; } } class JsonResult<T> : JsonResult { /* 子类重写属性解决JsON序列化属性顺序问题 */ overrIDe ResultCode resultCode { 数据 public T info { 接口成功返回数据 JsonResult(T info) { true ResultCode.OK; this.info = info; this.total = ; } } class JsonListResult<T>public List<T> info { public JsonListResult(List<T> List,1)">int total) { List; this.total = total; } public JsonListResult(List<T> List,PagerModel pager) { pager.totalRows; } } 结果编码 enum ResultCode { OK = 200100110021101110212011301130214011501 } 通用返回数据 CommonsubmitResult { 提示信息 string msg { 记录ID string ID { CommonMsgResult { ; } }}VIEw Code
异常拦截器
异常在这里统一处理,接口方法中不需要再加try catch
System.Web; System.Web.http.Filters; WebAPIDemo{ MyExceptionFilter : ExceptionFilterattribute { 重写基类的异常处理方法 OnException(httpActionExecutedContext actionExecutedContext) { var result = 拦截到异常: actionExecutedContext.Exception.Message,ResultCode.服务器内部错误); LogUtil.Error(actionExecutedContext.Exception); actionExecutedContext.Response = APIHelper.ToJson(result); base.OnException(actionExecutedContext); } }}VIEw Code
方法拦截器
1、在拦截器中校验证token
2、在拦截器中校验POST和GET参数
3、在拦截器中写 *** 作日志
Microsoft.Owin; Swashbuckle.Swagger; System.Collections.ObjectModel; System.Reflection; System.Web.http.Controllers; WebAPIDemo{ 拦截器 MyActionFilter : ActionFilterattribute { #region 变量 private Dictionary<string,1)">string> _dictActionDesc = ServiceHelper.Get<Dictionary<string>>(() => XmlUtil.GetActionDesc()); #region OnActionExecuting 执行方法前 执行方法前 OnActionExecuting(httpActionContext actionContext) { .OnActionExecuting(actionContext); token验证 Collection<AllowAnonymousAttribute> attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(); if (attributes.Count == 0) { IEnumerable<string> value; if (actionContext.Request.headers.TryGetValues(tokenout value)) { string token = value.ToArray()[]; if (false) todo:token验证 { actionContext.Response = APIHelper.ToJson(token不匹配或已过期; } } else { actionContext.Response = APIHelper.ToJson(请求头中不存在token; } } post参数验证 if (actionContext.Request.Method == httpMethod.Post) { foreach (string key in actionContext.ActionArguments.Keys) { object value = actionContext.ActionArguments[key]; if (value != ) { if (value.GetType().GetCustomAttributes(typeof(MyValIDateAttribute),1)">false).Length > ) { string errMsg = ; if (!ValIDatePropertyUtil.ValIDate(value,1)"> errMsg)) { JsonResult JsonResult = JsonResult(errMsg,ResultCode.参数不正确); actionContext.Response = APIHelper.ToJson(JsonResult); ; } } } } } get参数验证 httpMethod.Get) { if (key == pageif ((int)value <= ) { JsonResult JsonResult = page必须大于0; } } pageSizeint)value > 10000pageSize大于10000,请分页查询; } } } } } } #region OnActionExecutedAsync 执行方法后 执行方法后 overrIDe Task OnActionExecutedAsync(httpActionExecutedContext actionExecutedContext,CancellationToken cancellationToken) { return Task.Factory.StartNew(async () => { try { Type controllerType = actionExecutedContext.ActionContext.ControllerContext.Controller.GetType(); MethodInfo methodInfo = controllerType.getmethod(actionExecutedContext.ActionContext.ActionDescriptor.Actionname); string action = controllerType.Fullname + . methodInfo.name; if (_dictActionDesc.ContainsKey(action)) { string JsonResult = ; List<string> paramList = new List<(); string param = .Empty; if (actionExecutedContext.Request.Method == httpMethod.Post) { actionExecutedContext.ActionContext.ActionArguments.Keys) { actionExecutedContext.ActionContext.ActionArguments[key]; null && value as httpRequestMessage == ) { paramList.Add(JsonConvert.SerializeObject(value)); } } param = string.Join(if (actionExecutedContext.Exception == ) { byte[] barr = await actionExecutedContext.ActionContext.Response.Content.ReadAsByteArrayAsync(); JsonResult = EnCoding.UTF8.GetString(barr); } { JsonResult jr = new JsonResult(actionExecutedContext.Exception.Message + \r\n actionExecutedContext.Exception.StackTrace,ResultCode.服务器内部错误); JsonResult = JsonConvert.SerializeObject(jr); } } { ) { paramList.Add(key + = value.ToString()); } { paramList.Add(key + ); } } param = &if (actionExecutedContext.ActionContext.Response.Content is StringContent) { actionExecutedContext.ActionContext.Response.Content.ReadAsByteArrayAsync(); JsonResult = EnCoding.UTF8.GetString(barr); } { JsonResult = JsonConvert.SerializeObject(new JsonResult<object>()); } } JsonConvert.SerializeObject(jr); } } string ip = ; if (actionExecutedContext.Request.PropertIEs.ContainsKey(MS_OwinContext)) { OwinContext owinContext = actionExecutedContext.Request.PropertIEs["] as OwinContext; if (owinContext != { ip = owinContext.Request.RemoteIpAddress; } catch { } } } todo:写 *** 作日志 ServiceHelper.Get<SysOperLogDal>().Log(action,//方法名 actionExecutedContext.Request.Method,//请求类型 _dictActionDesc[action],//方法注释 ip,//IP actionExecutedContext.Request.RequestUri.LocalPath,//URL param,//请求参数 JsonResult); // *** 作结果 */ } } (Exception ex) { LogUtil.Error(ex,1)">MyActionFilter OnActionExecutedAsync 写 *** 作日志出错); } }); } }}VIEw Code
参数校验工具类
这里只做了必填和日期校验,且字段类型只是基础类型,有待完善
System.Globalization; 字段属性验证工具类 ValIDatePropertyUtil { 验证数据 true:验证通过 false 验证不通过 数据</param> <param name="errMsg">错误信息</param> bool ValIDate(object data,1)">out errMsg) { PropertyInfo[] propertyInfoList = data.GetType().GetPropertIEs(); foreach (PropertyInfo propertyInfo propertyInfoList) { if (propertyInfo.GetCustomAttributes(typeof(requiredAttribute),1)">) { propertyInfo.GetValue(data); if (value == ) { errMsg = 属性 " + propertyInfo.name + 必填return ; } } object[] attrArr = propertyInfo.GetCustomAttributes(typeof(DateTimeattribute),1)">); if (attrArr.Length > ) { DateTimeattribute attr = attrArr[0] DateTimeattribute; 是日期时间格式,格式: attr.Format; ; } { DateTime dt; if (!DateTime.TryParseExact(value.ToString(),attr.Format,CultureInfo.InvariantCulture,DateTimeStyles.None,1)"> dt)) { errMsg = attr.Format; ; } } } } errMsg = ; } }}VIEw Code
swagger.Js
复制到输出目录:不复制
生成 *** 作:嵌入的资源
var SwaggerTranslator = (function () { 定时执行检测是否转换成中文,最多执行500次 即500*50/1000=25s var _IExcute = 0; var _lock = 中文语言包 var _words = { "Warning: Deprecated": "警告:已过时" }; 定时执行转换 var _translator2Cn = () { if ($("#resources_container .resource").length > 0) { _tryTranslate(); } if ($("#explore").text() == "Explore" && _IExcute < 500) { _IExcute++; setTimeout(_translator2Cn,50); } }; 设置控制器注释 var _setControllerSummary = if (!_lock) { _lock = ; $.AJAX({ type: "get""#input_baseUrl").val(),dataType: "Json" (data) { var summaryDict = data.ControllerDesc; var ID,controllername,strSummary; $("#resources_container .resource").each( (i,item) { ID = $(item).attr("ID"); (ID) { controllername = ID.substring(9); strSummary = summaryDict[controllername]; (strSummary) { $(item).children(".heading").children(".options").prepend('<li title="' + strSummary + '">' + strSummary + '</li>'); } } }); setTimeout( () { _lock = ; },100); } }); } }; 尝试将英文转换成中文 var _tryTranslate = () { $('[data-sw-translate]').each( () { $(this).HTML(_getLangDesc($(this).HTML())); $(this).val(_getLangDesc($().val())); $(this).attr('Title',_getLangDesc($(this).attr('Title'))); }); }; var _getLangDesc = (word) { return _words[$.trim(word)] !== undefined ? _words[$.trim(word)] : word; }; { translate: () { document.Title = "API描述文档"; $('body').append('<style type="text/CSS">.controller-summary{color:#10a54a !important;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-wIDth:250px;text-align:right;cursor:default;} </style>'); $("#logo").HTML("接口描述").attr("href","/swagger/ui/index"); 设置控制器描述 _setControllerSummary(); _translator2Cn(); } };})();执行转换SwaggerTranslator.translate();VIEw Code
CachingSwaggerProvIDer.cs
System.IO; System.Xml; 用于汉化Swagger CachingSwaggerProvIDer : ISwaggerProvIDer { static ConcurrentDictionary<new ConcurrentDictionary<(); Readonly ISwaggerProvIDer _swaggerProvIDer; 构造函数 CachingSwaggerProvIDer(ISwaggerProvIDer swaggerProvIDer) { _swaggerProvIDer = swaggerProvIDer; } GetSwagger public Swaggerdocument GetSwagger(string rootUrl,1)"> APIVersion) { var cacheKey = string.Format({0}_{1}; 只读取一次 if (!_cache.TryGetValue(cacheKey,1)"> srcDoc)) { srcDoc = _swaggerProvIDer.GetSwagger(rootUrl,APIVersion); srcDoc.vendorExtensions = new Dictionary<object> { { ControllerDesc srcDoc; } { Swaggerdocument doc = Swaggerdocument(); doc.info = Info(); doc.info.Title = 接口不存在 doc; } } 从api文档中读取控制器描述 <returns>所有控制器描述</returns> GetControllerDesc() { string xmlpath = {0}/{1}.XML(SwaggerConfig).Assembly.Getname().name); ConcurrentDictionary<string> controllerDescDict = (file.Exists(xmlpath)) { Xmldocument xmldoc = Xmldocument(); xmldoc.Load(xmlpath); string type = string.Empty,path = .Empty; [] arrPath; int length = -1,cCount = Controller.Length; XmlNode summaryNode = foreach (XmlNode node in xmldoc.SelectNodes(//member)) { type = node.Attributes[name].Value; if (type.StartsWith(T:)) { 控制器 arrPath = type.Split(''); length = arrPath.Length; controllername = arrPath[length - 1]; if (controllername.EndsWith()) { 获取控制器注释 summaryNode = node.SelectSingleNode(summary); string key = controllername.Remove(controllername.Length - cCount,cCount); if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key)) { controllerDescDict.TryAdd(key,summaryNode.InnerText.Trim()); } } } } } controllerDescDict; } }}VIEw Code
SwaggerOperationFilter.cs
文件上传与token参数
System.Web.http.Description; SwaggerOperationFilter : IOperationFilter { Apply(Operation operation,SchemaRegistry schemaRegistry,APIDescription APIDescription) { if (operation.parameters == null) operation.parameters = new List<Parameter>if (APIDescription.relativePath.Contains(/Uploadfile)) { operation.parameters.RemoveAt(); operation.parameters.Add( Parameter { name = folderformData文件夹= string }); operation.parameters.Add(file文件 }); operation.consumes.Add(multipart/form-data); } Collection<AllowAnonymousAttribute> attributes = APIDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>) { operation.parameters.Insert(0,1)">new Parameter { name = headerTokentrue,type = }); } } }}VIEw Code
SwaggerConfig.cs
Swashbuckle.Application; System.Web;[assembly: PreApplicationStartMethod(typeof(SwaggerConfig),1)">Register)] SwaggerConfig { Register(httpConfiguration config) { var thisAssembly = (SwaggerConfig).Assembly; config .EnableSwagger(c => { By default,the service root url is inferred from the request used to access the docs. However,there may be situations (e.g. proxy and load-balanced environments) where this does not resolve correctly. You can workaround this by provIDing your own code to determine the root URL. // c.RootUrl(req => GetRootUrlFromAppConfig()); If schemes are not explicitly provIDed in a Swagger 2.0 document,then the scheme used to access the docs is taken as the default. If your API supports multiple schemes and you want to be explicit about them,you can use the "Schemes" option as shown below. c.Schemes(new[] { "http","https" }); Use "SingleAPIVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to hold additional Metadata for an API. Version and Title are required but you can also provIDe additional fIElds by chaining methods off SingleAPIVersion. // c.SingleAPIVersion(v1WebAPIDemo 测试接口文档); c.OperationFilter<SwaggerOperationFilter>(); 添加过滤器,增加Token令牌验证 c.IncludeXmlComments(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory,1)">@"WebAPIDemo.XML)); c.CustomProvIDer((defaultProvIDer) => new CachingSwaggerProvIDer(defaultProvIDer)); 汉化Swagger两步:第一步 If you want the output Swagger docs to be indented properly,enable the "PrettyPrint" option. c.PrettyPrint(); If your API has multiple versions,use "MultipleAPIVersions" instead of "SingleAPIVersion". In this case,you must provIDe a lambda that tells Swashbuckle which actions should be included in the docs for a given API version. like "SingleAPIVersion",each call to "Version" returns an "Info" builder so you can provIDe additional Metadata per API version. c.MultipleAPIVersions( (APIDesc,targetAPIVersion) => ResolveVersionSupportByRouteConstraint(APIDesc,targetAPIVersion), (vc) => { vc.Version("v2","Swashbuckle Dummy API V2"); vc.Version("v1","Swashbuckle Dummy API V1"); }); You can use "BasicAuth","APIKey" or "OAuth2" options to describe security schemes for the API. See https://github.com/swagger-API/swagger-spec/blob/master/versions/2.0.md for more details. NOTE: These only define the schemes and need to be coupled with a corresponding "security" property at the document or operation level to indicate which schemes are required for an operation. To do this,1)"> you'll need to implement a custom IdocumentFilter and/or IOperationFilter to set these propertIEs according to your specific authorization implementation c.BasicAuth("basic") .Description("Basic http Authentication"); NOTE: You must also configure 'EnableAPIKeySupport' below in the SwaggerUI section c.APIKey("APIKey") .Description("API Key Authentication") .name("APIKey") .In("header"); c.OAuth2("oauth2") .Description("OAuth2 Implicit Grant") .Flow("implicit") .AuthorizationUrl("http://petstore.swagger.wordnik.com/apI/Oauth/dialog") // .TokenUrl("https://tempuri.org/token .Scopes(scopes => scopes.Add("read","Read access to protected resources"); scopes.Add("write","Write access to protected resources"); Set this flag to omit descriptions for any actions decorated with the Obsolete attribute c.IgnoreObsoleteActions(); Each operation be assigned one or more Tags which are then used by consumers for varIoUs reasons. For example,the swagger-ui groups operations according to the first tag of each operation. overrIDe with any value. c.GroupActionsBy(APIDesc => APIDesc.httpMethod.ToString()); You can also specify a custom sort order for groups (as defined by "GroupActionsBy") to dictate the order in which operations are Listed. For example,if the default grouPing is in place (controller name) and you specify a descending Alphabetic sort order,then actions from a ProductsController will be Listed before those from a CustomersController. This is typically used to customize the order of grouPings in the swagger-ui. c.OrderActionGroupsBy(new DescendingAlphabeticComparer()); If you annotate Controllers and API Types with Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx),you can incorporate those comments into the generated docs and UI. You can enable this by provIDing the path to one or more Xml comment files. c.IncludeXmlComments(GetXmlCommentsPath()); Swashbuckle makes a best attempt at generating Swagger compliant JsON schemas for the varIoUs types exposed in your API. However,there may be occasions when more control of the output is needed. This is supported through the "MapType" and "SchemaFilter" options: Use the "MapType" option to overrIDe the Schema generation for a specific type. It should be noted that the resulting Schema will be placed "inline" for any applicable Operations. While Swagger 2.0 supports inline deFinitions for "all" Schema types,the swagger-ui tool does not. It expects "complex" Schemas to be defined separately and referenced. For this reason,you should only use the "MapType" option when the resulting Schema is a primitive or array type. If you need to alter a complex Schema,use a Schema filter. c.MapType<ProductType>(() => new Schema { type = "integer",format = "int32" }); If you want to post-modify "complex" Schemas once they've been generated,across the board or for a specific type,you can wire up one or more Schema filters. c.SchemaFilter<ApplySchemavendorExtensions>(); In a Swagger 2.0 document,complex types are typically declared globally and referenced by unique Schema ID. By default,Swashbuckle does NOT use the full type name in Schema IDs. In most cases,this works well because it prevents the "implementation detail" of type namespaces from leaking into your Swagger docs and UI. However,if you have multiple types in your API with the same class name,you'll need to opt out of this behavior to avoID Schema ID conflicts. c.UseFullTypenameInSchemaIDs(); Alternatively,you can provIDe your own custom strategy for inferring SchemaID's for describing "complex" types in your API. c.SchemaID(t => t.Fullname.Contains('`') ? t.Fullname.Substring(0,t.Fullname.IndexOf('`')) : t.Fullname); Set this flag to omit schema property descriptions for any type propertIEs decorated with the Obsolete attribute c.IgnoreObsoletePropertIEs(); In accordance with the built in JsonSerializer,Swashbuckle will,by default,describe enums as integers. You can change the serializer behavior by configuring the StringToEnumConverter globally or for a given enum type. Swashbuckle will honor this change out-of-the-Box. However,if you use a different approach to serialize enums as strings,you can also force Swashbuckle to describe them as strings. c.DescribeAllEnumsAsstrings(); Similar to Schema filters,Swashbuckle also supports Operation and document filters: Post-modify Operation descriptions once they've been generated by wiring up one or more Operation filters. c.OperationFilter<AddDefaultResponse>(); If you've defined an OAuth2 flow as described above,you Could use a custom filter to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required to execute the operation c.OperationFilter<AssignOAuth2SecurityRequirements>(); Post-modify the entire Swagger document by wiring up one or more document filters. This gives full control to modify the final Swaggerdocument. You should have a good understanding of the Swagger 2.0 spec. - https://github.com/swagger-API/swagger-spec/blob/master/versions/2.0.md before using this option. c.documentFilter<ApplydocumentvendorExtensions>(); In contrast to WebAPI,Swagger 2.0 does not include the query string component when mapPing a URL to an action. As a result,Swashbuckle will raise an exception if it encounters multiple actions with the same path (sans query string) and http method. You can workaround this by provIDing a custom strategy to pick a winner or merge the descriptions for the purposes of the Swagger docs c.ResolveConflictingActions(APIDescriptions => APIDescriptions.First()); Wrap the default SwaggerGenerator with additional behavior (e.g. caching) or provIDe an alternative implementation for ISwaggerProvIDer with the CustomProvIDer option. c.CustomProvIDer((defaultProvIDer) => new CachingSwaggerProvIDer(defaultProvIDer)); }) .EnableSwaggerUi(c => Use the "documentTitle" option to change the document Title. Very helpful when you have multiple Swagger pages open,to tell them apart. c.documentTitle("My Swagger UI"); Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets. The file must be included in your project as an "Embedded Resource",and then the resource's "Logical name" is passed to the method as shown below. c.InjectStylesheet(containingAssembly,"Swashbuckle.Dummy.SwaggerExtensions.testStyles1.CSS"); Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui has loaded. The file must be included in your project as an "Embedded Resource",1)"> "Logical name" is passed to the method as shown above. c.InjectJavaScript(thisAssembly,"Swashbuckle.Dummy.SwaggerExtensions.testScript1.Js"); The swagger-ui renders boolean data types as a dropdown. By default,it provIDes "true" and "false" strings as the possible choices. You can use this option to change these to something else,1)"> for example 0 and 1. c.BooleanValues(new[] { "0","1" }); in a badge at the bottom of the page. Use these options to set a different valIDator URL or to disable the feature entirely. c.SetValIDatorUrl("http://localhost/valIDator"); c.disableValIDator(); Use this option to control how the Operation Listing is displayed. It can be set to "None" (default),"List" (shows operations for each resource),1)"> or "Full" (fully expanded: shows operations and their details). c.DocExpansion(DocExpansion.List); Specify which http operations will have the 'Try it out!' option. An empty paramter List disables it for all operations. c.SupportedsubmitMethods("GET","head"); Use the CustomAsset option to provIDe your own version of assets used in the swagger-ui. It's typically used to instruct Swashbuckle to return your version instead of the default when a request is made for "index.HTML". As with all custom content,the file must be included in your project as an "Embedded Resource",and then the resource's "Logical name" is passed to the method as shown below. c.CustomAsset("index",containingAssembly,"YourWebAPIProject.SwaggerExtensions.index.HTML"); If your API has multiple versions and you've applIEd the MultipleAPIVersions setting as described above,you can also enable a select Box in the swagger-ui,that displays a discovery URL for each version. This provIDes a convenIEnt way for users to browse documentation for different API versions. c.EnablediscoveryUrlSelector(); If your API supports the OAuth2 Implicit flow,and you've described it correctly,according to the Swagger 2.0 specification,you can enable UI support as shown below. c.EnableOAuth2Support( clIEntID: "test-clIEnt-ID",1)"> clIEntSecret: null,1)"> realm: "test-realm",1)"> appname: "Swagger UI" additionalqueryStringParams: new Dictionary<string,string>() { { "foo","bar" } } ); If your API supports APIKey,you can overrIDe the default values. "APIKeyIn" can either be "query" or "header" c.EnableAPIKeySupport("APIKey","header"); c.InjectJavaScript(thisAssembly,1)">WebAPIDemo.Swagger.swagger.Js"); 汉化Swagger两步:第二步 }); } }}VIEw Code
辅助类XmlUtil.cs
XML工具类 XmlUtil { 从XML读取注释 <returns></returns> static Dictionary< GetActionDesc() { Dictionary<string> result = string xmlPath = (XmlUtil).Assembly.Getname().name); (file.Exists(xmlPath)) { Xmldocument xmlDoc = Xmldocument(); xmlDoc.Load(xmlPath); XmlNode summaryNode; string type; string desc; int pos; key; in xmlDoc.SelectNodes()) { type = type = node.Attributes[M:PrisonWebAPI.Controllers)) { pos = type.IndexOf((if (pos == -1) pos = type.Length; key = type.Substring(2,pos - 2); summaryNode = node.SelectSingleNode(); desc = summaryNode.InnerText.Trim(); result.Add(key,desc); } } } result; } }}VIEw Code
WebAPIHost工程的App.config
WebAPIDemo工程的Global.asax.cs和Web.config文件没有用了
<?xml version="1.0" enCoding="utf-8" ?><configuration> startup> supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </appSettings<!--Web API 服务端口号--> add key="WebAPIServicePort" value="8500" >>VIEw Code
在线文档截图
@H_318_2419@
总结
以上是内存溢出为你收集整理的ASP.NET Web API Demo OwinSelfHost 自宿主 Swagger Swashbuckle 在线文档全部内容,希望文章能够帮你解决ASP.NET Web API Demo OwinSelfHost 自宿主 Swagger Swashbuckle 在线文档所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)