首页 文章

http请求期间的操作无效

提问于
浏览
1

我正在写一个 windows forms 应用程序,用户必须输入电子邮件地址,我需要检查它是否有效 .

我找到 Mashape API 但是我得到了一个例外;

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

发生错误符合 msg.Headers.Add(header.Key, header.Value);

Value 观是:

  • header.Key = "Content-type"

  • header.Value = "application/json"

Debugger 说:

“确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用 . ”

我找不到任何解决方案,有没有人知道如何解决它?

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图书馆:

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);
    }

2 回答

  • 0

    错误消息说:

    “确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用 . ”

    Content-Type ,顾名思义,是一个内容 Headers . 因此,请将其设置为 msg.Content.Headers ,而不是 msg.Headers .

    如果我没记错的话,可以通过 msg.Content.Headers.ContentType = new MediaHeaderTypeValue("application/json"); 直接设置

  • 0

    好吧,它不起作用,因为Mashape提供的语法很糟糕 . 在这种情况下,header.Key必须是"ContentType"(参考:https://msdn.microsoft.com/en-us/library/system.net.httprequestheader%28v=vs.110%29.aspx) .

    对不起我的垃圾帖子,谢谢你@codran,你的回答帮我找到了这个答案 .

相关问题