0

我正在使用 jQuery 进行休息。

$.ajax({
                url: 'https://graylogurl/gelf',
                dataType: 'json',
                data: '{"short_message":"test message", "host":"localhost", "facility":"ajax", "_environment":"dev", "_meme":"yolo", "full_message":"this will contain a longer message"}',
                type: 'POST'
            });

这篇文章正确,可以满足我的需要。我尝试使用 C# 在我的 MVC4 控制器中做类似的事情

var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://graylogurl/gelf");
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";
        httpWebRequest.KeepAlive = false;

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"short_message\":\"test message\", \"host\":\"localhost\", \"facility\":\"ajax\", \"_environment\":\"dev\", \"_meme\":\"yolo\", \"full_message\":\"this is from the controller\"}";
            streamWriter.Write(json);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
        }

不幸的是,它总是超时。不知道我做错了什么。

4

1 回答 1

0

尝试更换:

httpWebRequest.ContentType = "text/json";

使用正确的内容类型:

httpWebRequest.ContentType = "application/json";

还要确保您已将 IDisposable 资源包装在using语句中,并使用WebClient适当的 JSON 序列化程序来构建您的 JSON 字符串似乎更容易、更正确:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var data = new JavaScriptSerializer().Serialize(new
    {
        short_message = "test message",
        host = "localhost",
        facility = "ajax",
        _environment = "dev",
        _meme = "yolo",
        full_message = "this is from the controller",
    });
    var resultData = client.UploadData("https://graylogurl/gelf", Encoding.UTF8.GeBytes(data));
    string result = Encoding.UTF8.GetString(resultData);
}

还要确保托管 ASP.NET 应用程序的服务器可以访问您尝试访问的远程 URL,并且没有防火墙阻止它。如果您有任何疑问,请联系您的网络管理员,但为了能够执行此 HTTP 请求,远程 URL 必须可通过托管应用程序的 Web 服务器的 443 端口 (HTTPS) 访问。

于 2013-08-05T21:16:28.510 回答