2009-10-22 7 views
5

Sto costruendo un'applicazione in ASP.NET MVC (utilizzando C#) e vorrei sapere come posso eseguire chiamate come arricciatura http://www.mywebsite.com/clients_list.xml all'interno del mio controller Fondamentalmente mi piacerebbe costruire una specie di API REST per eseguire azioni come show edit e delete, come l'API di Twitter.ASP.NET MVC - Utilizzo di cURL o simile per eseguire richieste nell'applicazione

Ma purtroppo fino ad ora non ho trovato nulla oltre che cURL per le finestre su questo sito: http://curl.haxx.se/

Quindi non so se esiste un modo tradizionale per recuperare questo tipo di chiamata da URL con i metodi come post cancellare e inserire richieste, ecc ...

Mi piacerebbe solo sapere un modo semplice per eseguire comandi come curl all'interno del mio controller sulla mia applicazione ASP.NET MVC.


UPDATE:

Hi così sono riuscito a fare richieste GET, ma ora sto avendo un grave problema in recuperare POST Richiesta per esempio, sto utilizzando l'API stato di aggiornamento di Twitter che a ricciolo dovrebbe funzionare in questo modo:

curl -u user:password -d "status=playing with cURL and the Twitter API" http://twitter.com/statuses/update.xml 

ma sulla mia applicazione ASP.NET MVC che sto facendo in questo modo dentro la mia funzione personalizzata:

string responseText = String.Empty; 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); 
request.Method = "POST"; 
request.Credentials = new NetworkCredential("username", "password"); 
request.Headers.Add("status", "Tweeting from ASP.NET MVC C#"); 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
using (StreamReader sr = new StreamReader(response.GetResponseStream())) 
{ 
    responseText = sr.ReadToEnd(); 
} 
return responseText; 

Ora il problema è che questa richiesta sta tornando 403 Forbidden, io davvero non so perché se funziona perfettamente su ricciolo

: \


UPDATE:

finalmente riesco per farlo funzionare, ma probabilmente c'è un modo per renderlo più pulito e bello, dato che sono nuovo su C# Avrò bisogno di più conoscenza per farlo, il modo in cui vengono passati i parametri POST mi rende molto confuso perché è un sacco di codice per passare semplicemente i parametri.

Bene, ho creato un Gist - http://gist.github.com/215900, quindi tutti si sentono liberi di rivederlo come preferisci. Grazie per il vostro aiuto Çağdaş

seguire anche il codice qui:

public string TwitterCurl() 
{ 
    //PREVENT RESPONSE 417 - EXPECTATION FAILED 
    System.Net.ServicePointManager.Expect100Continue = false; 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); 
    request.Method = "POST"; 
    request.Credentials = new NetworkCredential("twitterUsername", "twitterPassword"); 

    //DECLARE POST PARAMS 
    string headerVars = String.Format("status={0}", "Tweeting from ASP.NET MVC C#"); 
    request.ContentLength = headerVars.Length; 

    //SEND INFORMATION 
    using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream(), ASCIIEncoding.ASCII)) 
    { 
     streamWriter.Write(headerVars); 
     streamWriter.Close(); 
    } 

    //RETRIEVE RESPONSE 
    string responseText = String.Empty; 
    using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream())) 
    { 
     responseText = sr.ReadToEnd(); 
    } 

    return responseText; 

    /* 
    //I'M NOT SURE WHAT THIS IS FOR    
     request.Timeout = 500000; 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.UserAgent = "Custom Twitter Agent"; 
     #if USE_PROXY 
      request.Proxy = new WebProxy("http://localhost:3000", false); 
     #endif 
    */ 
} 
+0

I parametri di nome utente e password sono supposti come credenziali di rete o dati di post semplici? Non conosco l'API di Twitter, quindi sarebbe meglio se spiegassi cosa stai cercando di fare esattamente. –

+0

BTW, sembra che potresti ottenere uno stato proibito 403 se hai raggiunto; 1. 1.000 aggiornamenti totali al limite del giorno. 2. 250 messaggi diretti totali al limite giornaliero. 3. 150 richieste API per limite orario. http://help.twitter.com/forums/10711/entries/15364 –

+0

scusa, beh, in questo caso si sta tentando di connettersi al mio account Twitter da http://twitter.com/statuses/update.xml, quindi se provate ad accedere a questo dal vostro browser vedrete che richiede un nome utente e una password in modo che le credenziali su questo caso siano il nome utente e la password del mio account twitter, che stavo pensando che sarebbe lo stesso di curl -u username: password ... Quindi, in questo metodo l'applicazione si collegherà al mio account Twitter, invierà un nuovo tweet che invierà il parametro "status" + credenziali e recupererà la risposta che Twitter invierà di nuovo un file xml in questo caso. – zanona

risposta

3

Provare a usare Microsoft.Http.HttpClient.Questo è ciò che la vostra richiesta sarà simile

var client = new HttpClient(); 
client.DefaultHeaders.Authorization = Credential.CreateBasic("username","password"); 

var form = new HttpUrlEncodedForm(); 
form.Add("status","Test tweet using Microsoft.Http.HttpClient"); 
var content = form.CreateHttpContent(); 

var resp = client.Post("http://www.twitter.com/statuses/update.xml", content); 
string result = resp.Content.ReadAsString(); 

È possibile trovare questa biblioteca e la sua fonte incluso nel WCF REST Starter kit Preview 2, ma può essere utilizzato indipendentemente dal resto della roba lì.

P.S. Ho testato questo codice sul mio account Twitter e funziona.

+0

Ciao Darrel, Grazie per questo sembra molto semplice, ma sfortunatamente per errore non riesco a trovare le classi HttpClient e HttpUrlEncodedForm, ho già installato questa libreria WCF ma non riesco a trovarla, anche su libreria Microsoft, in realtà non c'è Microsoft Spazio dei nomi http qui, sono sicuro che sto facendo qualcosa di sbagliato. Scusa – zanona

+0

Sulla mia macchina, la dll è qui C: \ Programmi (x86) \ Microsoft WCF REST \ WCF REST Starter Kit Anteprima 2 \ Assemblies. Inoltre, incluso nel programma di installazione è un file zip che contiene il codice sorgente. Aprilo e la fonte completa è lì dentro. –

0

Guardare in System.Net. WebClient classe. Dovrebbe offrire la funzionalità richiesta. Per un controllo a grana fine, potresti trovare WebRequest più utile, ma WebClient sembra il più adatto alle tue esigenze.

2

codice di esempio utilizzando HttpWebRequest e HttpWebResponse:

public string GetResponseText(string url) { 
    string responseText = String.Empty; 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
    request.Method = "GET"; 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    using (StreamReader sr = new StreamReader(response.GetResponseStream())) { 
     responseText = sr.ReadToEnd(); 
    } 
    return responseText; 
} 

per inviare i dati:

public string GetResponseText(string url, string postData) { 
    string responseText = String.Empty; 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
    request.Method = "POST"; 
    request.ContentLength = postData.Length; 
    using (StreamWriter sw = new StreamWriter(request.GetRequestStream())) { 
     sw.Write(postData); 
    } 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    using (StreamReader sr = new StreamReader(response.GetResponseStream())) { 
     responseText = sr.ReadToEnd(); 
    } 
    return responseText; 
} 
+0

grazie mille per questo çağdaş, ora sto avendo un altro problema, ho modificato la domanda in modo da poter controllare lì, se ti piace. grazie ancora – zanona

1

Questa è la singola riga di codice che utilizzo per le chiamate a un'API RESTful che restituisce JSON.

return ((dynamic) JsonConvert.DeserializeObject<ExpandoObject>(
     new WebClient().DownloadString(
      GetUri(surveyId)) 
    )).data; 

Note

  • Uri è generato fuori fase utilizzando il surveyId e le credenziali
  • La proprietà 'dati' è parte dell'oggetto de-serializzato JSON restituito dal SurveyGizmo API

Il servizio completo

public static class SurveyGizmoService 
{ 
    public static string UserName { get { return WebConfigurationManager.AppSettings["SurveyGizmo.UserName"]; } } 
    public static string Password { get { return WebConfigurationManager.AppSettings["SurveyGizmo.Password"]; } } 
    public static string ApiUri { get { return WebConfigurationManager.AppSettings["SurveyGizmo.ApiUri"]; } } 
    public static string SurveyId { get { return WebConfigurationManager.AppSettings["SurveyGizmo.Survey"]; } } 

    public static dynamic GetSurvey(string surveyId = null) 
    { 
     return ((dynamic) JsonConvert.DeserializeObject<ExpandoObject>(
       new WebClient().DownloadString(
        GetUri(surveyId)) 
      )).data; 
    } 

    private static Uri GetUri(string surveyId = null) 
    { 
     if (surveyId == null) surveyId = SurveyId; 
     return new UriBuilder(ApiUri) 
       { 
         Path = "/head/survey/" + surveyId, 
         Query = String.Format("user:pass={0}:{1}", UserName, Password) 
       }.Uri; 
    } 
} 
Problemi correlati