1
votes

I spent 3 days reading all the articles related here and on other websites, about this error, without success! Now I need help.

ERROR:

{StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{
...server's informations...
Strict-Transport-Security: max-age=2592000
X-Android-Received-Millis: 1551400026958
X-Android-Response-Source: NETWORK 415X-
Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1551400026857
X-Powered-By: ASP.NETContent-Length: 0}}

METHOD: The problem appear in: request.PostAsync(URL, param).GetAwaiter().GetResult();

public static string RegisterPerson(Person p)
{
string msg = "";
string URL = URLbase + "person/register"; //--URL RIGHT, TESTING IN POSTMAN, INSERT DATA NORMALLY
   FormUrlEncodedContent param = new FormUrlEncodedContent(new[] {
    new KeyValuePair<string, string>("Name", p.Name),
    new KeyValuePair<string, string>("Phone", p.Fone),
    new KeyValuePair<string, string>("Birth", p.Birth),
});

HttpClient request = new HttpClient();
request.DefaultRequestHeaders.Accept.Clear();
request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = request.PostAsync(URL, param).GetAwaiter().GetResult(); // <===ERROR HERE

switch (response.StatusCode)
{
case HttpStatusCode.OK:
msg= "SUCCESS";
break;
....

Thank you in advance!

2
this is a server error - without knowing anything about the server you're connecting to its probably impossible to answer. - Jason
You are assigning an MediaTypeWithQualityHeaderValue of json and not sending json data. Also use await instead of .GetAwaiter().GetResult(), another deadlock just waiting to happen... - SushiHangover
HttpClient request = new HttpClient(); is a sure-fire way to use up all of the available system sockets if you call RegisterPerson often. - Llama

2 Answers

0
votes

This is an old question, but since no accepted answers exist yet with code example, I am posting an answer here. Hopefully this answer with code example will be helpful to someone else who stumbles on this question, like I did. I struggled for a few minutes between application/json, FormUrlEncodedContent, Content-Type header, etc. and then finally got it working. As under...

Option 1, using PostAsync...

var url = "https://....your url goes here...";
var param = new Dictionary<string, string>
{
    { "key_one", "value_1" },
    { "key_two", "value_2" }
    // ... and so on
};
var content = new FormUrlEncodedContent(param);
var response = _httpClient.PostAsync(url, content);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
    throw new Exception(result);
}
return "process result object into anything you need and then return it";

Option 2, using SendAsync...

var url = "https://....your url goes here...";
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
var param = new Dictionary<string, string>
{
    { "key_one", "value_1" },
    { "key_two", "value_2" }
    // ... and so on
};
var content = new FormUrlEncodedContent(param);
request.Content = content;
var response = _httpClient.SendAsync(request);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
    throw new Exception(result);
}

return "process result object into anything you need and then return it";

In case anyone is going to copy/paste this code, please note, _httpClient object in above snippet was first initialized in IoC and then injected into constructor. You can do however your needs are. Since "how to use IoC" is not a part of this question, I am going into that detail.

0
votes

So to answer the question first, I would bet you need to set a "Content-Type" header as it is complaining about a wrong media type being provided (You are setting what you are willing to accept, but not what you are sending). Also does the service expect application/x-www-form-urlencoded encoded content (that is what you are sending)? If so provide that as the Content-Type, but it is less usual these days to do so.

Is this classic WebApi or .net Core? I am asking as if it is the latter, change your method to be non-static, inject IHttpClientFactory and use it to construct your client. The benefit is you can create clients that suit your needs at injection (Startup.cs) and re-use them and also avoid socket issues at scale (mind you this requires a lot of load, so if this is not what you are in for don't worry). It does make for cleaner Controller code however, so it maybe worthwhile from a code readability perspective which to me is generally what I optimize on.