在 Visual Studio 2010 中,我使用 ASP.NET MVC 4 创建 Web API 项目,如本示例所示:https://www.youtube.com/watch?v=H9vBxAH4f5E
一切正常 - 我使用 GET
方法成功了,但是当使用 POST
方法时,我遇到了一个问题:
No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'application/x-www-form-urlencoded'.
我的 webapiconfig.cs
看起来像这样:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
FormUrlEncodedMediaTypeFormatter f;
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
f = new FormUrlEncodedMediaTypeFormatter();
f.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Formatters.Add(f);
// application/x-www-form-urlencoded ???
}
}
为什么我遇到了问题:
No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'application/x-www-form-urlencoded'.
完整的错误信息:
Message: "An error has occurred." ExceptionMessage: "No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'application/x-www-form-urlencoded'." ExceptionType: "System.InvalidOperationException" StackTrace: " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable
1 formatters, IFormatterLogger formatterLogger) at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable
1 formatters, IFormatterLogger formatterLogger) at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) at System.Web.Http.Controllers.HttpActionBinding.<>c__DisplayClass1.b__0(HttpParameterBinding parameterBinder) at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext() at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator
1 enumerator, CancellationToken cancellationToken)"
请求头:
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36 Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo Content-Type: application/x-www-form-urlencoded Accept: */* Accept-Encoding: gzip,deflate Accept-Language: he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4
响应头:
Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Mon, 08 Sep 2014 18:06:10 GMT Content-Length: 1111
我该如何解决这个问题?
谢谢:)
最佳答案
您应该只需要将新的媒体类型添加到支持的格式列表中:
f = new FormUrlEncodedMediaTypeFormatter();
f.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
f.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x-www-form-urlencoded"));
关于c# - ASP.NET MVC 4 - 使用 post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25729184/