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

时间:2009-10-22 08:39:53

标签: asp.net-mvc api rest curl twitter

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

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

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

我只是想知道一种简单的方法来在我的ASP.NET MVC应用程序中执行控制器内的curl等命令。


更新:

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

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

但是在我的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;

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

:\


更新:

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

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

也请遵循以下代码:

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 个答案:

答案 0 :(得分:3)

尝试使用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();

您可以在WCF REST Starter kit Preview 2中找到此库及其来源,但它可以独立于其中的其他内容使用。

P.S。我在我的推特账户上测试了这段代码,但它确实有用。

答案 1 :(得分:2)

使用HttpWebRequestHttpWebResponse的示例代码:

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

要发布数据:

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

答案 2 :(得分:1)

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

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

备注

  • 使用surveyId和凭据
  • 在舞台上生成Uri
  • 'data'属性是返回的反序列化JSON对象的一部分 通过SurveyGizmo API

完整服务

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

答案 3 :(得分:0)

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