2013-08-05 48 views
0

我正在使用jQuery進行休息。jQuery.ajax在C#中休息後等效#

$.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' 
      }); 

這篇文章正確,適用於我需要的東西。我試圖在我的MVC4控制器中使用C#做類似的事情。

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

不幸的是,它總是超時。不知道我做錯了什麼。

回答

0

嘗試更換:

httpWebRequest.ContentType = "text/json"; 

有了正確的內容類型:

httpWebRequest.ContentType = "application/json"; 

還要確保您已在using陳述包裹IDisposable的資源,並使用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)訪問。