0
votes

I am writing a service with POST request as:

    [HttpPost]
    [ActionName("Post")]
    public HttpResponseMessage Post([FromBody]string JStringCont)
    {
       ....
    }

Call to this service is given as:

    string jsonContent="[{some json}]"
    StringContent content = new StringContent(jsonContent);
    _oHttpClient = new HttpClient();
    _oHttpClient.DefaultRequestHeaders.Accept.Clear();
_oHttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

response = _oHttpClient.PostAsync(requestURI, content).Result;

Service is clearly getting called through sending a parameter stringcontent. I am not allowed to change the way service is getting called.

I can make changes in service itself.
POST method is not able to accept in the string format. What can be the parameter which I can use over there in POST request which will accept stringcontent??

Currently it is giving me Error:

Response: UnsupportedMediaType

{"Message":"The request entity's media type 'text/plain' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

2
Have you tried JsonResult?Amit Mishra
Tried sending Content-Type header with value application/json?Chetan
I am not allowed to touch the code where service is getting called.. I want to make service as per it has got calledC Sharper

2 Answers

3
votes

You should allow JsonMediaTypeFormatter parses requests with Content-Type: text/plain. So on startup your application (in Startup.cs or WebApiConfig.cs file) you need -

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));

config is HttpConfiguration object.

0
votes

System.AggregateException: One or more errors occurred. ---> System.Net.Http.UnsupportedMediaTypeException: No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'.

I was getting above error while doing put call with return type as string,

I used putasync with return type as Task string.

The issue got resolved, this should work for you as well