ASP.NET MVC - 使用cURL或类似方法在应用程序中执行请求

时间:2022-11-01 04:12:03

I'm building an application in ASP.NET MVC (using C#) and I would like to know how I can perform calls like curl http://www.mywebsite.com/clients_list.xml inside my controller Basically I would like to build a kind of REST API to perform actions such as show edit and delete, such as Twitter API.

我正在ASP.NET MVC中构建一个应用程序(使用C#),我想知道如何在我的控制器内执行像curl http://www.mywebsite.com/clients_list.xml这样的调用基本上我想构建一种REST API,用于执行show edit和delete等操作,例如Twitter API。

But unfortunately until now I didn't find anything besides that cURL for windows on this website: http://curl.haxx.se/

但不幸的是,到目前为止,除了本网站上的cURL for windows之外,我没有找到任何东西:http://curl.haxx.se/

So I don't know if is there any traditional way to retrieve this kind of call from URL with methods like post delete and put on the requests, etc...

所以我不知道是否有任何传统的方法从URL中检索这种类型的调用方法,如删除后删除请求等等...

I just would like to know an easy way to perform commands like curl inside my controller on my ASP.NET MVC Application.

我只想知道在ASP.NET MVC应用程序中执行控制器内部卷曲等命令的简单方法。


UPDATE:

Hi so I managed to make GET Requests but now I'm having a serious problem in retrieve POST Request for example, I'm using the update status API from Twitter that in curl would work like this:

嗨所以我设法做了GET请求但是现在我在检索POST请求时遇到了严重的问题,例如,我正在使用来自Twitter的更新状态API,在curl中会像这样工作:

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

but on my ASP.NET MVC application I'm doing like this inside my custom function:

但在我的ASP.NET MVC应用程序中,我在我的自定义函数中这样做:

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;

Now the problem is that this request is returning 403 Forbidden, I really don't know why if it works perfectly on curl

现在问题是这个请求正在返回403 Forbidden,我真的不知道为什么它在curl上完美运行

:\


UPDATE:

I finally manage to get it working, but probably there's a way to make it cleaner and beautiful, as I'm new on C# I'll need more knowledge to do it, the way the POST params are passed makes me very confused because is a lot of code to just pass params.

我终于设法让它工作,但可能有一种方法可以让它变得更清洁和漂亮,因为我是C#的新手,我需要更多的知识才能做到这一点,POST params传递的方式让我非常困惑因为是很多代码只能传递params。

Well, I've created a Gist - http://gist.github.com/215900 , so everybody feel free to revise it as you will. Thanks for your help çağdaş

好吧,我已经创建了一个Gist - http://gist.github.com/215900,所以每个人都可以随意修改它。谢谢你的帮助çağdaş

also follow the code here:

也按照这里的代码:

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
    */
}

4 个解决方案

#1


3  

Try using Microsoft.Http.HttpClient. This is what your request would look like

尝试使用Microsoft.Http.HttpClient。这就是您的请求的样子

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();

You can find this library and its source included in the WCF REST Starter kit Preview 2, however it can be used independently of the rest of the stuff in there.

您可以在WCF REST Starter工具包预览2中找到此库及其源代码,但它可以独立于其中的其他内容使用。

P.S. I tested this code on my twitter account and it works.

附:我在我的推特账户上测试了这段代码并且它有效。

#2


2  

Example code using HttpWebRequest and HttpWebResponse :

使用HttpWebRequest和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;
}

To POST data :

要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;
}

#3


1  

This is the single line of code I use for calls to a RESTful API that returns JSON.

这是我用于调用返回JSON的RESTful API的单行代码。

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

Notes

  • The Uri is generated off stage using the surveyId and credentials
  • 使用surveyId和凭证生成Uri

  • The 'data' property is part of the de-serialized JSON object returned by the SurveyGizmo API
  • 'data'属性是SurveyGizmo API返回的反序列化JSON对象的一部分

The Complete Service

完整的服务

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;
    }
}

#4


0  

Look into the System.Net.WebClient class. It should offer the functionality you require. For finer grained control, you might find WebRequest to be more useful, but WebClient seems the best fit for your needs.

查看System.Net.WebClient类。它应该提供您需要的功能。对于更精细的控制,您可能会发现WebRequest更有用,但WebClient似乎最适合您的需求。

#1


3  

Try using Microsoft.Http.HttpClient. This is what your request would look like

尝试使用Microsoft.Http.HttpClient。这就是您的请求的样子

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();

You can find this library and its source included in the WCF REST Starter kit Preview 2, however it can be used independently of the rest of the stuff in there.

您可以在WCF REST Starter工具包预览2中找到此库及其源代码,但它可以独立于其中的其他内容使用。

P.S. I tested this code on my twitter account and it works.

附:我在我的推特账户上测试了这段代码并且它有效。

#2


2  

Example code using HttpWebRequest and HttpWebResponse :

使用HttpWebRequest和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;
}

To POST data :

要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;
}

#3


1  

This is the single line of code I use for calls to a RESTful API that returns JSON.

这是我用于调用返回JSON的RESTful API的单行代码。

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

Notes

  • The Uri is generated off stage using the surveyId and credentials
  • 使用surveyId和凭证生成Uri

  • The 'data' property is part of the de-serialized JSON object returned by the SurveyGizmo API
  • 'data'属性是SurveyGizmo API返回的反序列化JSON对象的一部分

The Complete Service

完整的服务

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;
    }
}

#4


0  

Look into the System.Net.WebClient class. It should offer the functionality you require. For finer grained control, you might find WebRequest to be more useful, but WebClient seems the best fit for your needs.

查看System.Net.WebClient类。它应该提供您需要的功能。对于更精细的控制,您可能会发现WebRequest更有用,但WebClient似乎最适合您的需求。