ASP.NET MVC 4 - using post method
In Visual Studio 2010 I am using ASP.NET MVC 4 to create a web project api like in this example: https://www.youtube.com/watch?v=H9vBxAH4f5E
Everything works fine - I manage to use the method GET
, but when using the method POST
I have a problem:
No MediaTypeFormatter is available to read a 'String' object from content with media type "application / x-www-form-urlencoded".
Mine webapiconfig.cs
looks like this:
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 ???
}
}
Why I am facing the problem:
No MediaTypeFormatter is available to read a 'String' object from content with media type "application / x-www-form-urlencoded".
Complete error message:
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 Formatter, IFormatterLogger formatterLogger) at System.Web.Http.ModelBindingcindingCinding ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancelationToken) in System.Web.Http.Controllers.HttpActionBinding <.> C__DisplayClass1.b__0 (HttpParameterBinding parameterBinderWeb) when System.Linq.EnumerableIndicator is2.MoveNext() at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator
1CancellationToken cancelationToken) "
Request header:
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
Response header:
Cache-Control: no-cache Pragma: no-cache Content-Type: Usage / 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
How can I solve the problem?
Thank:)
source to share