WebAPI HelpPage出现Failed to generate the sample for media type 'application/x-www-form-urlencoded'. 错

WebApi参数页面的示例里,出现如下错误:

Failed to generate the sample for media type 'application/x-www-form-urlencoded'. Cannot use formatter 'JQueryMvcFormUrlEncodedFormatter' to write type 'Vehicle'.

调试查了一下原因,是因为WebAPI的Formatter里,存在一个类型为System.Web.Http.ModelBinding.JQueryMvcFormUrlEncodedFormatter的Formatter,而HelpPage又没有对进行对应的解析导致的。本来想改HelpPage代码,但想想其实不需要,只要把这个Formattter在WebAPI里移除就可以了,如下:


在App_Start的WebApiConfig.cs的Register方法里,加下如下这句将其移除:

config.Formatters.Remove(config.Formatters.FirstOrDefault(p => p.GetType() == typeof(System.Web.Http.ModelBinding.JQueryMvcFormUrlEncodedFormatter)));

如果你只要JSON格式,其它不要,可以这样写:

config.Formatters.Clear();
config.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());

这句的意思是先将Formatter全部清除,再添加你想要的Formatter,这里用了Json,如果要XML,则

config.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());

参考:

https://stackoverflow.com/questions/18249344/exclude-media-type-sample-from-web-api-help-page

猜你喜欢

转载自blog.csdn.net/winnyrain/article/details/78246905
今日推荐