none
client c# mengunakan server django RRS feed

  • Pertanyaan

  • mohon bantuannya saya.
    dapat tugas dari tempat magang untuk menghubungkan c# dengan django(framework python).
    sudah saya coba selama 1 bulan tapi masih tetap gagal.
    di server nya menggunakan csrftoken. error yang saya dapat di saat debug yaitu 403 forbidden untuk disisi client sedangkan disisi server yaitu csrftoken missing .
    terimakasih

    
    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
        {
            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 wc = new WebClient();
    
    
                CookieContainer cookieJar = new CookieContainer();
    
               var request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/api/");
                request.CookieContainer = cookieJar;
    
                var response = request.GetResponse();
    
                string baseSiteString = wc.DownloadString("http://localhost/api/");
                //    string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
               
              // wc.Headers.Add("X-CSRF-Token", csrfToken);
                wc.Headers.Add("X-Requested-With", "XMLHttpRequest");
                using (HttpWebResponse response1 = (HttpWebResponse)request.GetResponse())
                {
                    foreach (Cookie cookie1 in response1.Cookies)
                    {
                        string cookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie];//(response as HttpWebResponse).Headers[HttpResponseHeader.SetCookie];
                        Console.WriteLine(baseSiteString);
                        //Console.WriteLine("CSRF Token: {0}", csrfToken);
                        Console.WriteLine("Cookie: {0}", cookie);
    
    
                        wc.Headers.Add(HttpRequestHeader.Cookie, cookie);
                        wc.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 csrfmiddlewaretoken =cookie1.Name +"="+cookie1.Value;
    
                        string csrf = string.Join(cookie, ARG1, ARG2);
    
                        //string dataString =cookie;
                        // string dataString = @"{""user"":{""email"":"""+uEmail+@""",""password"":"""+uPassword+@"""}}";
                        string dataString = @"{""user"":{""csrfmiddlewaretoken"":""" + csrfmiddlewaretoken + @""",""ARG1"":""" + ARG1 + @""",""ARG2"":""" + ARG2 + @"""}}";
                        byte[] dataBytes = Encoding.ASCII.GetBytes(dataString);
    
                        byte[] responseBytes = wc.UploadData(new Uri("http://localhost/api/multiplyfunction/"), "POST", dataBytes);
                        string responseString = Encoding.ASCII.GetString(responseBytes);
                        Console.WriteLine(responseString);
                        Console.WriteLine("value=" + cookie1.Value);
                        Console.WriteLine("name=" + cookie1.Name);
                        Console.WriteLine();
                        //Console.Write((int)response.StatusCode);
                        //PostRespone("http://localhost/api/multiplyfunction/");
                    }
                }
               
    
               /* Console.Write("\nPlease enter the URI to post data to : ");
                string uriString = Console.ReadLine();
                // Create a new WebClient instance.
                WebClient myWebClient = new WebClient();
                Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:", uriString);
                string postData = Console.ReadLine();
                // Apply ASCII Encoding to obtain the string as a byte array.
                byte[] postArray = Encoding.ASCII.GetBytes(postData);
                Console.WriteLine("Uploading to {0} ...", uriString);
                myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    
                //UploadData implicitly sets HTTP POST as the request method.
                byte[] responseArray = myWebClient.UploadData(uriString, postArray);
    
                // Decode and display the response.
                Console.WriteLine("\nResponse received was :{0}", Encoding.ASCII.GetString(responseArray));
                */
    
            }
    
    
        }
    
        }
    
    
     


    Selasa, 15 November 2016 03.13

Semua Balasan

  • apa udah dibuat loginRequest.Headers.Add("X-CSRFToken",csrf token value) ?


    • Diedit oleh britishdhez Rabu, 16 November 2016 04.30
    • Disarankan sebagai Jawaban oleh britishdhez Senin, 21 November 2016 05.43
    • Saran Jawaban dibatalkan oleh britishdhez Senin, 21 November 2016 08.45
    Rabu, 16 November 2016 04.30
  • x-csrftoken ini base nya apa gan?
    apa bisa di console atau windows form?

    Senin, 21 November 2016 07.06
  • https://docs.djangoproject.com/en/1.10/ref/csrf/

    oh iya yak, dia base Ajax si, karena keknya masalahnya autentifikasi

    http://stackoverflow.com/questions/10663446/post-method-always-return-403-forbidden


    • Diedit oleh britishdhez Senin, 21 November 2016 09.03
    Senin, 21 November 2016 09.03
  • ini belum pake auth gan.

    masih coba menghubungkan biasa.. 
    Senin, 21 November 2016 09.25
  • ini belum pake auth gan.

    masih coba menghubungkan biasa.. 
    import requests
    session = requests.Session()
    resp = session.get('http://localhost/api/')
    print("Session : ",resp)
    qqq=resp.cookies['csrftoken']
    
    """
    API : Multiplication
    """
    data={'csrfmiddlewaretoken':qqq,'ARG1' :100,'ARG2':5} 
    url = 'http://localhost/api/multiplyfunction/'
    resp=session.post(url,data=data)
    print("Resp API: ",resp.text)
    
    """
    API : Get Status
    """
    data={'ARG':100} 
    url = 'http://localhost/api/statusfunction/'
    resp=session.get(url,params={'ARG':"NET1"})
    
    print("Resp API: ",resp.text)

    yang saya tanyakan kenapa disisi client c# kok masih error sedangkan pake client django sendiri sudah run.?
    mohon bantuannya


    • Diedit oleh jack karang Senin, 21 November 2016 09.30
    Senin, 21 November 2016 09.28
  • udah di konekin di visual studio nya kan? coba manual pake cara dibawah

    https://blogs.msdn.microsoft.com/cdndevs/2014/10/27/part-6-get-started-with-python-build-your-first-django-application-in-ptvs/


    • Diedit oleh britishdhez Selasa, 22 November 2016 04.45
    Selasa, 22 November 2016 04.44
  • semua yang di django udah run gan.

    ini tinggal error di c# nya aja.
    gimana cara set value cookie nya saja.
    Selasa, 22 November 2016 07.03
  • gini ya

    https://forums.asp.net/t/1279490.aspx

    http://www.codelocker.net/99/get-and-set-cookie-values-in-dot-net/

    https://www.mindstick.com/Articles/1293/cookies-in-asp-dot-net-c-sharp

    saya emang ga ada pengalaman ma Django si, tapi di artikel ini bilang

    https://www.twilio.com/blog/2014/04/building-a-simple-sms-message-application-with-twilio-and-django-2.html

    we’ve received a 403 forbidden response. Because Django is strict about security, especially when it comes to HTTP POST requests, it requires a CSRF token to validate the requests. To get around this you need to add a csrf_exempt decorator

    Makanya dugaaan saya ni Django butuh login atau autentifikasi pake CSRF token

    Tapi kalo di bilang Django nya jalan dan setting di VS nya dah bener, coba deh Tanya forum Django juga

    karena kalo ASP.NET berikut kemungkianannya

    https://support.microsoft.com/en-us/kb/822322

    http://www.codeproject.com/Questions/470636/why-i-see-Error-in-my-asp-net-website


    • Diedit oleh britishdhez Selasa, 22 November 2016 08.46
    Selasa, 22 November 2016 08.46