ASP.NET MVC - 使用cURL或类似的在应用程序中执行请求 [英] ASP.NET MVC - Using cURL or similar to perform requests in application

查看:772
本文介绍了ASP.NET MVC - 使用cURL或类似的在应用程序中执行请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET MVC(使用C#)中构建应用程序,我想知道如何执行调用curl http://www.mywebsite.com/clients_list.xml 在我的控制器
基本上,我想构建一种REST API来执行操作,如显示编辑和



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



所以我不知道是否有任何传统的方式,从URL中检索这种类型的呼叫,如邮政删除和放在请求等等...



我只是想知道






更新:



您好,所以我设法做GET请求,但现在我有一个严重的问题,在检索POST请求,例如,我使用更新状态API从Twitter的curl将工作像这样:

  curl -u user:password -dstatus =使用cURL和Twitter APIhttp:// 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,Tweets 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



:\






UPDATE:



我终于设法让它工作,但可能有一个方法,使它更清洁和美丽,因为我是新的C#我将需要更多的知识做到这一点,POST params传递的方式让我非常困惑,因为很多代码只是传递params。



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



也按照此处的代码:

  public string TwitterCurl()
{
//预防响应417 - 期望失败
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;

//发送信息
使用(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;

/ *
//我不知道这是为
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
* /
}


解决方案

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

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

var form = new HttpUrlEncodedForm();
form.Add(status,使用Microsoft.Http.HttpClient测试tweet);
var content = form.CreateHttpContent();

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

您可以找到此库及其源代码包含在 WCF REST入门套件预览2 ,但它可以独立于其余的东西使用。 p>

PS我在我的Twitter帐户上测试了这个代码,它的工作原理。


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.

But unfortunately until now I didn't find anything besides that cURL for windows on this website: 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...

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


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:

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:

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

:\


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.

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ş

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

解决方案

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

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.

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

这篇关于ASP.NET MVC - 使用cURL或类似的在应用程序中执行请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆