ASP.NET MVC: utilizzo di cURL o simile per eseguire richieste nell'applicazione
-
05-07-2019 - |
Domanda
Sto creando un'applicazione in ASP.NET MVC (usando C #) e vorrei sapere come posso eseguire chiamate come curl http://www.mywebsite.com/clients_list.xml all'interno del mio controller Fondamentalmente vorrei creare una sorta di API REST per eseguire azioni come mostra modifica ed elimina, come l'API di Twitter.
Ma sfortunatamente fino ad ora non ho trovato nulla oltre a quel cURL per Windows su questo sito Web: http: // curl .haxx.se /
Quindi non so se esiste un modo tradizionale per recuperare questo tipo di chiamata dall'URL con metodi come post elimina e invia le richieste, ecc ...
Vorrei solo sapere un modo semplice per eseguire comandi come arricciatura all'interno del mio controller sulla mia applicazione ASP.NET MVC.
UPDATE:
Ciao, quindi sono riuscito a fare richieste GET, ma ora sto riscontrando un serio problema nel recupero della richiesta POST, ad esempio, sto usando l'API di stato dell'aggiornamento da Twitter che in curl funzionerebbe 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 sto facendo così all'interno della 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 restituendo 403 Proibito, Davvero non so perché se funziona perfettamente su arricciatura
: \
UPDATE:
Finalmente riesco a farlo funzionare, ma probabilmente c'è un modo per renderlo più pulito e bello, dato che sono nuovo su C # avrò bisogno di maggiori conoscenze per farlo, il modo in cui i parametri POST sono passati mi rende molto confuso perché è un sacco di codice per passare solo i parametri.
Bene, ho creato un Gist - http://gist.github.com/215900, quindi tutti si sentono liberi di rivederlo come vuoi. Grazie per il tuo aiuto çagdas
segui 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
*/
}
Soluzione
Prova a utilizzare Microsoft.Http.HttpClient. Ecco come sarebbe la tua richiesta
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();
Puoi trovare questa libreria e la sua fonte inclusa nel Starter kit WCF REST Anteprima 2 , tuttavia può essere utilizzata indipendentemente dal resto delle cose presenti.
P.S. Ho testato questo codice sul mio account Twitter e funziona.
Altri suggerimenti
Codice di esempio usando 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 i dati POST:
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;
}
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
- L'URI viene generato fuori dal palco utilizzando il surveyId e le credenziali
- La proprietà 'data' fa parte dell'oggetto JSON non serializzato restituito dall'API SurveyGizmo
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;
}
}
Cerca in System.Net. WebClient classe. Dovrebbe offrire la funzionalità richiesta. Per un controllo più preciso, potresti trovare WebRequest per essere più utile, ma WebClient sembra la soluzione migliore per le tue esigenze.