标签:
Asp.net MVC WebAPI 生成帮助文档时对于API的参数是自定义类型的会遇到本错误。
API.Areas.HelpPage.HelpPageConfig 的 Register 方法中 可以将以下代码注释去掉以消除该错误。
//// 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);
解决 Failed to generate the sample for media type 'application/x-www-form-urlencoded'.
标签:
原文地址:http://www.cnblogs.com/leonworld/p/4453812.html