C# 无法在asp.net mvc中实现将tweet与图像一起发送到twitter
我正在asp.NETMVC上工作。我正在尝试实现twitter的tweet机制,包括文本和图像,并在twitter中将其作为tweet发送。我遵循了由提供的文档。我遵循Twitterizer库完成了这一步,但它向我抛出了错误,就像API版本1已被弃用一样,尽管我使用的是最新版本,并且它适用于除此之外的其他端点。所以我决定自己发出http请求 在我的例子中,我的表单中有textarea和文件上传控件C# 无法在asp.net mvc中实现将tweet与图像一起发送到twitter,c#,asp.net,asp.net-mvc,twitter,C#,Asp.net,Asp.net Mvc,Twitter,我正在asp.NETMVC上工作。我正在尝试实现twitter的tweet机制,包括文本和图像,并在twitter中将其作为tweet发送。我遵循了由提供的文档。我遵循Twitterizer库完成了这一步,但它向我抛出了错误,就像API版本1已被弃用一样,尽管我使用的是最新版本,并且它适用于除此之外的其他端点。所以我决定自己发出http请求 在我的例子中,我的表单中有textarea和文件上传控件 <form method="post" action="/Home/Upload" enct
<form method="post" action="/Home/Upload" enctype="multipart/form-data">
<textarea id="message" name="message"></textarea>
<input type="file" name="file"/>
<input type="submit" value="submit"/>
</form>
之后,在我的动作中,我得到了用户选择的图像和他输入到我的动作中的文本。我已将HttpPostedFileBase转换为字节[],如下所示
[HttpPost]
public ActionResult Upload(FormCollection coll, HttpPostedFileBase upfile)
{
byte[] data;
using (Stream inputStream = upfile.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
HttpWebRequest webRequest = WebRequest.Create("https://api.twitter.com/1.1/statuses/update_with_media.json") as HttpWebRequest;
OAuthBase oauth = new OAuthBase();
string nonce = oauth.GenerateNonce();
string timeStamp = oauth.GenerateTimeStamp();
string normalizedUrl;
string normalizedRequestParameters;
string sig = oauth.GenerateSignature
(new System.Uri("https://api.twitter.com/1.1/statuses/update_with_media.json"), consumerKey, consumerSecret, userinfo.AuthToken,
userinfo.PayUserId, "POST", timeStamp, nonce,
OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl,
out normalizedRequestParameters);
string header = string.Format(@"OAuth oauth_consumer_key=""{0}"",oauth_signature_method=""{1}"",oauth_timestamp=""{2}"",oauth_nonce=""{3}"",oauth_version=""{4}"",oauth_token=""{5}"",oauth_signature=""{6}""",
HttpUtility.UrlEncode(consumerKey), HttpUtility.UrlEncode("HMAC-SHA1"), HttpUtility.UrlEncode(timeStamp), HttpUtility.UrlEncode(nonce), HttpUtility.UrlEncode("1.0"), HttpUtility.UrlEncode(userinfo.AuthToken), HttpUtility.UrlEncode(sig));
webRequest.Headers.Add("Authorization", header);
webRequest.Method = "POST";
webRequest.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)webRequest).UserAgent = ".NET Framework Example Client";
Dictionary<string, object> fieldsToInclude = new Dictionary<string, object>();
fieldsToInclude.Add("status", coll["new_message"]);
fieldsToInclude.Add("media[]", data);
string boundary = Guid.NewGuid().ToString().Replace("-", "");
string dataBoundary = "--------------------r4nd0m";
string contentType = "multipart/form-data; boundary=" + dataBoundary;
byte[] mydata = GetMultipartFormData(fieldsToInclude, contentType);
webRequest.ContentLength = mydata.Length;
webRequest.ContentType = contentType;
using (Stream requestStream = webRequest.GetRequestStream())
{
if (mydata != null)
{
requestStream.Write(mydata, 0, mydata.Length);
}
}
using (HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
string retVal = reader.ReadToEnd();
}
return View();
}
[HttpPost]
公共操作结果上载(FormCollection coll、HttpPostedFileBase upfile)
{
字节[]数据;
使用(Stream inputStream=upfile.inputStream)
{
MemoryStream MemoryStream=作为MemoryStream的输入流;
if(memoryStream==null)
{
memoryStream=新的memoryStream();
inputStream.CopyTo(memoryStream);
}
data=memoryStream.ToArray();
}
HttpWebRequest webRequest=webRequest.Create(“https://api.twitter.com/1.1/statuses/update_with_media.json)作为HttpWebRequest;
OAuthBase oauth=新的OAuthBase();
字符串nonce=oauth.generateOnce();
字符串timeStamp=oauth.GenerateTimeStamp();
字符串规范化;
字符串参数;
字符串sig=oauth.GenerateSignature
(新的System.Uri(“https://api.twitter.com/1.1/statuses/update_with_media.json“”、consumerKey、ConsumerCret、userinfo.AuthToken、,
userinfo.PayUserId,“POST”,时间戳,nonce,
OAuthBase.SignatureTypes.HMACSHA1,out normalizedUrl,
out(请求参数);
string header=string.Format(@“OAuth OAuth_consumer_key=”“{0}”、OAuth_signature_method=“{1}”、OAuth_timestamp=“{2}”、OAuth_nonce=“{3}”、OAuth_version=“{4}”、OAuth_token=“{5}”、OAuth_signature=“{6}”,
HttpUtility.UrlEncode(consumerKey)、HttpUtility.UrlEncode(“HMAC-SHA1”)、HttpUtility.UrlEncode(时间戳)、HttpUtility.UrlEncode(nonce)、HttpUtility.UrlEncode(“1.0”)、HttpUtility.UrlEncode(userinfo.AuthToken)、HttpUtility.UrlEncode(sig));
添加(“授权”,标题);
webRequest.Method=“POST”;
webRequest.Credentials=CredentialCache.DefaultCredentials;
((HttpWebRequest)webRequest.UserAgent=“.NET Framework示例客户端”;
字典字段stoinclude=新字典();
fieldsToInclude.Add(“状态”,coll[“新消息”);
fieldsToInclude.Add(“媒体[]”,数据);
字符串边界=Guid.NewGuid().ToString().Replace(“-”,”);
字符串dataBoundary=“--------------r4nd0m”;
string contentType=“多部分/表单数据;boundary=“+dataBoundary;
字节[]mydata=GetMultipartFormData(fieldsToInclude,contentType);
webRequest.ContentLength=mydata.Length;
webRequest.ContentType=ContentType;
使用(Stream requestStream=webRequest.GetRequestStream())
{
if(mydata!=null)
{
Write(mydata,0,mydata.Length);
}
}
使用(HttpWebResponse webResponse=webRequest.GetResponse()作为HttpWebResponse)
{
StreamReader=新的StreamReader(webResponse.GetResponseStream());
string retVal=reader.ReadToEnd();
}
返回视图();
}
在这里,我编写了一种为图像和文本数据准备多部分formdata结构的方法,如
private byte[] GetMultipartFormData(Dictionary<string, object> fieldsToInclude, string boundary)
{
Stream formDataStream = new MemoryStream();
Encoding encoding = Encoding.UTF8;
foreach (KeyValuePair<string, object> kvp in fieldsToInclude)
{
if (kvp.Value.GetType() == typeof(byte[]))
{ //assume this to be a byte stream
byte[] data = (byte[])kvp.Value;
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: application/octet-stream\r\n\r\n",
boundary,
kvp.Key,
kvp.Key);
byte[] headerBytes = encoding.GetBytes(header);
formDataStream.Write(headerBytes, 0, headerBytes.Length);
formDataStream.Write(data, 0, data.Length);
}
else
{ //this is normal text data
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
boundary,
kvp.Key,
kvp.Value);
byte[] headerBytes = encoding.GetBytes(header);
formDataStream.Write(headerBytes, 0, headerBytes.Length);
}
}
string footer = string.Format("\r\n--{0}--\r\n", boundary);
formDataStream.Write(encoding.GetBytes(footer), 0, footer.Length);
formDataStream.Position = 0;
byte[] returndata = new byte[formDataStream.Length];
formDataStream.Read(returndata, 0, returndata.Length);
formDataStream.Close();
return returndata;
}
private byte[]GetMultipartFormData(字典字段stoinclude,字符串边界)
{
Stream formDataStream=newmemoryStream();
编码=Encoding.UTF8;
foreach(字段中的KeyValuePair kvp包括)
{
if(kvp.Value.GetType()==typeof(byte[]))
{//假设这是一个字节流
字节[]数据=(字节[])kvp.Value;
string header=string.Format(“--{0}\r\n内容配置:表单数据;名称=\“{1}\”;文件名=\“{2}\”;\r\n内容类型:应用程序/八位字节流\r\n\r\n”,
边界,
kvp.Key,
kvp.Key);
byte[]headerBytes=encoding.GetBytes(header);
formDataStream.Write(headerBytes,0,headerBytes.Length);
formDataStream.Write(data,0,data.Length);
}
其他的
{//这是正常的文本数据
string header=string.Format(“--{0}\r\n内容处理:表单数据;名称=\“{1}\”\r\n\r\n{2}\r\n”,
边界,
kvp.Key,
kvp值);
byte[]headerBytes=encoding.GetBytes(header);
formDataStream.Write(headerBytes,0,headerBytes.Length);
}
}
string footer=string.Format(“\r\n--{0}--\r\n”,边界);
写入(encoding.GetBytes(footer),0,footer.Length);
formDataStream.Position=0;
byte[]returndata=新字节[formDataStream.Length];
读取(returndata,0,returndata.Length);
formDataStream.Close();
返回数据;
}
这就是我所遵循的方式,通过http请求将图像上传到twitter(也称为媒体上传)。但是我犯了错误
static void TweetWithMediaDemo(TwitterContext twitterCtx)
{
string status = "Testing TweetWithMedia #Linq2Twitter " + DateTime.Now.ToString(CultureInfo.InvariantCulture);
const bool possiblySensitive = false;
const decimal latitude = StatusExtensions.NoCoordinate; //37.78215m;
const decimal longitude = StatusExtensions.NoCoordinate; // -122.40060m;
const bool displayCoordinates = false;
const string replaceThisWithYourImageLocation = @"..\..\images\200xColor_2.png";
var mediaItems =
new List<Media>
{
new Media
{
Data = Utilities.GetFileBytes(replaceThisWithYourImageLocation),
FileName = "200xColor_2.png",
ContentType = MediaContentType.Png
}
};
Status tweet = twitterCtx.TweetWithMedia(
status, possiblySensitive, latitude, longitude,
null, displayCoordinates, mediaItems, null);
Console.WriteLine("Media item sent - Tweet Text: " + tweet.Text);
}
private void sharetwitter ()
{
var oauth_consumer_key = "your API key";
var oauth_consumer_secret = "Your API secret key";
string token = "access token";
string tokenSecret = "access token secret ";
var post = db.Posts.Where(p => p.PostId ==id).FirstOrDefault();
StringBuilder str = new StringBuilder();
str.AppendLine(post.Title.Trim());
str.AppendLine("learn .net a lot of helpful programming stuffs.");
var service = new TweetSharp.TwitterService(oauth_consumer_key,oauth_consumer_secret);
service.AuthenticateWith(token, tokenSecret);
string url = "http://www.infinetsoft.com/Images/logoinfi.png";
service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = str.ToString(),
Images = new Dictionary<string, Stream> { { "infinetsoft", urltostream(url) } }
});
TempData["SuccessMessage"] = "tweeted success";
}
var imageBinary = File.ReadAllBytes("path");
var media = Upload.UploadImage(imageBinary);
var tweet = Tweet.PublishTweet("hello", new PublishTweetOptionalParameters
{
Medias = { media }
});