asp.net-web-api – 在Web API 2中使用属性路由时限制自动帮助页
我目前正在使用Web API 2的属性路由(
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2)实现Web API.我还使用帮助页面模块,以便从XML注释(
http://www.asp.net/web-api/overview/creating-web-apis/creating-api-help-pages)自动生成文档.
对于这个API,我提供了对可选返回格式扩展的支持,因此每个API方法都有一对定义的路由,如下所示: [HttpGet] [Route("Path/Foo")] [Route("Path/Foo.{ext}")] public HttpResponseMessage DoFoo() { // Some API function. } 这允许用户点击其中任何一个并获得结果: www.example.com/api/Controller/Path/Foo www.example.com/api/Controller/Path/Foo.json www.example.com/api/Controller/Path/Foo.xml 我的问题是,当帮助页面使用MapHttpAttributeRoutes()生成文档时,它会为每个方法选择两个路径.所以现在我看到帮助: api/Controller/Foo api/Controller/Foo.{ext} 但我只想看到: api/Controller/Foo.{ext} 我宁愿在每个方法上隐藏非扩展路由,这样每个方法只显示一个帮助页面条目. 有没有其他人尝试类似的东西?有没有我失踪的工作? 解决方法
我的问题是,你的api的消费者会轻易搞清楚{ext}是可选的吗?…就个人而言,我更喜欢默认行为……但无论如何以下是我能想到的一些解决方法:
>快速而肮脏的解决方法.将DoFoo拆分为2个动作,如DoFoo()和DoFooWithExt.请注意,我使用的是名为ApiExplorerSettings的属性,用于HelpPage目的.示例如下: [HttpGet] [Route("Path/Foo")] [ApiExplorerSettings(IgnoreApi=true)] public HttpResponseMessage DoFoo() { return DoFooHelper(); } [HttpGet] [Route("Path/Foo.{ext}")] public HttpResponseMessage DoFooWithExt() { return DoFooHelper(); } private HttpResponseMessage DoFooHelper() { //do something } >创建自定义ApiExplorer(HelpPage功能在内部使用)并检查特定路径,如下所示,并可决定是否显示该特定路径的操作. // update the config with this custom implementation config.Services.Replace(typeof(IApiExplorer),new CustomApiExplorer(config)); public class CustomApiExplorer : ApiExplorer { public CustomApiExplorer(HttpConfiguration config) : base(config) { } public override bool ShouldExploreAction(string actionVariableValue,HttpActionDescriptor actionDescriptor,IHttpRoute route) { if (route.RouteTemplate.EndsWith("Path/Foo",StringComparison.OrdinalIgnoreCase)) { return false; } return base.ShouldExploreAction(actionVariableValue,actionDescriptor,route); } } >从默认的ApiExplorer获取所有ApiDescription列表,然后过滤掉您不喜欢的描述.例:Configuration.Services.GetApiExplorer().ApiDescriptions.Where((apiDesc)=>!apiDesc.RelativePath.EndsWith(“Path / Foo”,StringComparison.OrdinalIgnoreCase)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – Visual Studio 2012 – 哪里有ASPX设计和拆分视
- 在asp.net中查看状态
- asp.net – 如何防止Hangfire重复作业在连续执行30分钟后重
- asp.net-mvc – 具有Fluent nHibernate和Ninject的多租户.每
- asp.net-mvc – ASP.net MVC返回文件和重定向
- 在ASP.NET Web应用程序中有未处理的异常是否可以接受?
- asp.net – 如何单元测试使用HostingEnvironment.MapPath的
- ASP.Net – 在没有Windows用户的情况下使用基本身份验证
- asp.net-mvc – 如何在不创建多个动作结果的情况下将字符串
- asp.net-mvc-2 – 在发布网站后无法在asp.net mvc2中加载类
- asp.net – 来自WebHttpBinding的WCF服务中的Acc
- asp.net-mvc – SelectList选择的值未转移到Drop
- asp.net – 如何使用占位符属性与Html.EditorFor
- 在IIS托管的asp.net Web应用程序中打开页面时“无
- asp.net – BC30560:’ExtensionAttribute’在名
- 浅谈ASP.NET配置文件加密
- asp.net-mvc-2 – <::<%:和<%=与嵌套代码(表
- asp.net – “HttpContext.Current”属性和相关事
- 定时器_在.net core3.0 webapi中添加自定义定时器
- asp.net – DotLess的“web”属性究竟做了什么?