2016-11-24 45 views
-1

我想連接Django API與c#但是當我連接我面臨C#中的問題。如何連接api django 1.10與c#

Django這裏我用作服務器API和C#作爲客戶端。 C#中的錯誤是「CSRF丟失或不正確」。

using System; 
using System.Net; 
using System.IO; 
using System.Text; 
using System.Collections.Generic; 
using System.Net.Http; 
using System.Collections.Specialized; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     private static string json; 

     public static string url { get; private set; } 

     static void Main(string[] args) 
     { 

      /* 

       try 
       { 

        CookieContainer container = new CookieContainer(); 
        HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/api/"); 
        request1.Proxy = null; 
        request1.CookieContainer = container; 
        using (HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse()) 
        { 
         foreach (Cookie cookie1 in response1.Cookies) 
         { 

          //Console.WriteLine(response.IsSuccessStatusCode); 
          var csrf = cookie1.Value; 
          Console.WriteLine(csrf); 
          Console.WriteLine("name=" + cookie1.Name); 
          Console.WriteLine(); 
          Console.Write((int)response1.StatusCode); 
          //PostRespone("http://localhost/api/multiplyfunction/"); 

         } 

        } 

       } 

       catch (WebException e) 
       { 
        Console.WriteLine(e.Status); 
       } 
       /* HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/"); 
       request.CookieContainer = Cookie; // use the global cookie variable 
       string postData = "100"; 
       byte[] data = Encoding.UTF8.GetBytes(postData); 
       request.Method = "POST"; 
       request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; 
       request.ContentLength = data.Length; 

       using (Stream stream = request.GetRequestStream()) 
       { 
        stream.Write(data, 0, data.Length); 
       } 

       WebResponse response = (HttpWebResponse)request.GetResponse(); 
       string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();*/ 
      WebClient csrfmiddlewaretoken = new WebClient(); 


      CookieContainer cookieJar = new CookieContainer(); 

      var request1 = (HttpWebRequest)HttpWebRequest.Create("http://localhost/api/"); 
      request1.CookieContainer = cookieJar; 

      var response1 = request1.GetResponse(); 

      string baseSiteString = csrfmiddlewaretoken.DownloadString("http://localhost/api/"); 
      // string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value; 

      // wc.Headers.Add("X-CSRF-Token", csrfToken); 
      csrfmiddlewaretoken.Headers.Add("X-Requested-With", "XMLHttpRequest"); 
      using (HttpWebResponse response2 = (HttpWebResponse)request1.GetResponse()) 
      { 
       foreach (Cookie cookie1 in response2.Cookies) 
       { 
        //string cookie = csrfmiddlewaretoken.ResponseHeaders[HttpResponseHeader.SetCookie];//(response as HttpWebResponse).Headers[HttpResponseHeader.SetCookie]; 
        Console.WriteLine(baseSiteString); 
        //Console.WriteLine("CSRF Token: {0}", csrfToken); 
        //Console.WriteLine("Cookie: {0}", cookie); 
// 


        csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8"); 
        //wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01"); 
        var csrf1 = cookie1.Value; 
        string ARG1 = ("100"); 
        string ARG2 = ("5"); 
        string ARG = ("ARG"); 
        string csrfmiddlewaretoken1 =cookie1.Name +"="+cookie1.Value; 
        csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.Cookie, csrfmiddlewaretoken1); 
        //string csrf = string.Join(cookie, ARG1, ARG2); 

        //string dataString =cookie; 
        // string dataString = @"{""user"":{""email"":"""[email protected]""",""password"":"""[email protected]"""}}"; 
        string dataString = "{\"ARG1\": \"100\", \"ARG2\": \"5\"}"; 
        // string dataString = "csrftokenmiddlewaretoken="+csrfmiddlewaretoken; 
        //dataString += "&ARG1=10"; 
        //dataString += "&ARG2=10"; 
        byte[] dataBytes = Encoding.ASCII.GetBytes(dataString); 
        //byte[] respon2 = csrfmiddlewaretoken.DownloadData(new Uri("http://localhost/api/statusfunction/")); 
        WebRequest request = WebRequest.Create("http://localhost/api/statusfunction/?ARG"); 

        // Get the response. 
        HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

        // Get the stream containing content returned by the server. 
        Stream dataStream = response.GetResponseStream(); 
        // Open the stream using a StreamReader for easy access. 
        StreamReader reader = new StreamReader(dataStream); 
        // Read the content. 
        string responseFromServer = reader.ReadToEnd(); 
        // Display the content. 
        Console.WriteLine(responseFromServer); 


        byte[] responseBytes = csrfmiddlewaretoken.UploadData(new Uri("http://localhost/api/multiplyfunction/"), "POST", dataBytes); 
        string responseString = Encoding.UTF8.GetString(responseBytes); 
        Console.WriteLine(responseString); 
        // byte[] res = csrfmiddlewaretoken.UploadFile("http://localhost/api/multiplyfunction/", @"ARG1:100"); 


        // Console.WriteLine(result); 

        Console.WriteLine("value=" + cookie1.Value); 
        Console.WriteLine("name=" + cookie1.Name); 
        Console.WriteLine(); 
        Console.Write((int)response2.StatusCode); 
        // PostRespone("http://localhost/api/multiplyfunction/"); 

       } 
      } 
     } 
    } 
} 
+0

那麼你需要提供csrf令牌。這與c#無關, –

+0

我在python中做了下面的代碼: –

回答

0

你在你的Django視圖中接受POST請求嗎?如果是的話,你應該使用@csrf_exempt修飾器來處理POST請求。另一種選擇是從C#端提供CSRF令牌。