2

I'm writing a windows forms app where user have to enter email address and I need to check if it's valid.

I have found Mashape API but I get an exception;

"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Net.Http.dll" error in Unirest library.

Error occurs in line with msg.Headers.Add(header.Key, header.Value);

Values are:

  • header.Key = "Content-type"
  • header.Value = "application/json"

Debugger says:

"Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

I can't find any solution, does anyone has any idea how to fix it?

    Task<HttpResponse<EWSemail>> response = Unirest.post("https://email.p.mashape.com/")
    .header("X-Mashape-Key", myKey)
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .body("{\"email\":\"" + tbEmail.Text + "\"}")
    .asJsonAsync<EWSemail>();

Unirest library:

    private static Task<HttpResponseMessage> RequestHelper(HttpRequest request)
    {
        if (!request.Headers.ContainsKey("user-agent"))
        {
            request.Headers.Add("user-agent", USER_AGENT);
        }

        var client = new HttpClient();
        var msg = new HttpRequestMessage(request.HttpMethod, request.URL);

        foreach (var header in request.Headers)
        {
            msg.Headers.Add(header.Key, header.Value);
        }                 //   ^^"Content-Type"  ^^ "application/json"

        if (request.Body.Any())
        {
            msg.Content = request.Body;
        }

        return client.SendAsync(msg);
    }
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Laguland
  • 65
  • 1
  • 7

2 Answers2

0

The error message says:

"Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

Content-Type, as the name would imply, is a content header. Therefore, set it on msg.Content.Headers, not msg.Headers.

If I remember correctly, you can set it directly via msg.Content.Headers.ContentType = new MediaHeaderTypeValue("application/json");

yaakov
  • 5,552
  • 35
  • 48
0

OK, it doesn't work because syntax that Mashape provide is bad. In this case header.Key has to be "ContentType" (Reference: https://msdn.microsoft.com/en-us/library/system.net.httprequestheader%28v=vs.110%29.aspx).

I'm sorry for my rubbish post and thank you @codran, your answer helped me to find this answer.

Laguland
  • 65
  • 1
  • 7