解决 Failed to generate the sample for media type 'application/x-www-form-urlencoded'.
Asp.net MVC WebAPI 生成帮助文档时对于API的参数是自定义类型的会遇到本错误。
API.Areas.HelpPage.HelpPageConfig 的 Register 方法中 可以将以下代码注释去掉以消除该错误。
1 2 3 | //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); |
但是针对不同的自定义类型,如果在帮助文档中都返回 "[0]=foo&[1]=bar" 字符串的话 明显是无法将Post的参数一一列出的,而且也无法根据自定义参数的属性类型进行定制。
解决的方法如下:
- 新建一个基类
public class Parameter { public void Reg (HttpConfiguration config){ Assembly _Assembyle = Assembly.GetAssembly(this.GetType()); List<Type> supportedClass = _Assembyle.GetTypes().Where(t => t.BaseType != null && t.BaseType.Name == "Parameter").ToList(); foreach (var s in supportedClass) { string str = ""; PropertyInfo[] ps = s.GetProperties(); foreach (var p in ps) { switch (p.PropertyType.Name) { case "Guid": str += p.Name + "=" + Guid.NewGuid().ToString(); break; case "int": case "long": str += p.Name + "=1000" ; break; default: str += p.Name + "=" +p.Name; break; } str += "&"; } str=str.TrimEnd('&'); config.SetSampleForType(str, new MediaTypeHeaderValue("application/x-www-form-urlencoded"), s); } }
2. Post的参数类继承基类
public class TestResultComponentVersion_body : Parameter { /// <summary> /// TestResultId /// </summary> public Guid TestResultId { get; set; } /// <summary> /// ComponentName /// </summary> public string ComponentName { get; set; } /// <summary> /// ComponentVersion /// </summary> public string ComponentVersion { get; set; } }
3. API.Areas.HelpPage.HelpPageConfig 的 Register 方法中调用Reg方法
new Parameter().Reg(config);
标签:
Asp.net WebAPI
posted on 2015-04-24 16:24 leonworld2011 阅读(1302) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构