2017-02-26 86 views
0

對不起,我的英語JSON發送到另一臺服務器。使用asp.net mvc的核心C#

我需要JSON發送到另一臺服務器。

例子:127.0.0.1/api/start

在這個其他的服務器我有我創建運行服務,服務需要得到一個JSON

示例{「SERVERID」:「1」 「ServerPort」: 「27015」}

我怎樣才能做到這一點?

我知道用jQuery發送JSON,但我想知道如何不使用jQuery做到這一點使用asp.net核心。有可能嗎?

public IActionResult Start() 
    { 

     // Code here 

     return View(); 
    } 

我需要使用asp.net核心做這個代碼

var arr = { ServerId : '1', ServerPort : '27015'}; 
      console.log(JSON.stringify(arr));    
      return jQuery.ajax({ 
       headers: { 
        'Accept': 'application/json', 
        'Content-Type': 'application/json' 
       }, 
       'type': 'POST', 
       'url': '13.77.102.81/Api/MTA/Start', 
       'data': JSON.stringify(arr), 
       'dataType': 'json', 
       'success': function (msg) { 
        console.log(msg); 
       } 
      }); 

回答

0

你必須改變這樣的

public IActionResult Start() 
    { 


    var jsonRequest = Json(new { ServerId = "1", ServerPort = "27015" }).Value.ToString(); 
        HttpClient client = new HttpClient(); 
        client.BaseAddress = new Uri("http://13.77.102.81/api/mta/start "); 
        client.DefaultRequestHeaders 
          .Accept 
          .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header 

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress"); 

        request.Content = new StringContent(jsonRequest, 
                 Encoding.UTF8, 
                 "application/json");//CONTENT-TYPE header 

        client.SendAsync(request) 
          .ContinueWith(responseTask => 
          { 
           //here your response 
           Debug.WriteLine("Response: {0}", responseTask.Result); 
          }); 
     return View(); 
    } 

,並在這裏你的方法什麼響應

Response: StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
    Connection: keep-alive 
    Date: Sun, 26 Feb 2017 21:43:26 GMT 
    Server: nginx/1.4.6 
    Server: (Ubuntu) 
    Content-Length: 0 
} 

所以你的服務器沒有運行或你的代理做的請求:)過濾器

當你問一個問題

+0

HM ..但IP,我需要發送JSON是13.77.102.81,不要暴露你的IP這裏我具體該? –

+0

更準確的說是要送13.77.102.81/api/mta/start –

+0

或您的服務發送GET請求?有兩件事 –