简体   繁体   English

MVC-来自Controller的推文无法正常运行

[英]MVC - Tweet from Controller not working well

I have a problem with Twitter tweet from my application, I don't understand why not working. 我的应用程序中的Twitter tweet有问题,我不明白为什么不起作用。

This is my code: 这是我的代码:

TwitterHelper.Tweet(Message, Request,
     unitOfWork.UserProfileRepository.GetByID(WebSecurity.CurrentUserId).ToString());

If I use my code from the Controller's ActionResult Index... method or from Edit method, working fine. 如果我使用Controller的ActionResult Index...方法或Edit方法的代码,则工作正常。

But If I use from my own 但是如果我自己使用

ActionResult SendTweet(string message) 
{
    ...

it is not working. 它不起作用。 No error message, just not reaching the twitter, don't want to authenticate, etc. 没有错误消息,只是没有到达Twitter,不想进行身份验证等。

I call this method from my view with ajax 我用ajax从我的观点调用此方法

$.ajax({
    url: "/MyController/SendTweet",
    type: "POST",
    dataType: "json",
    data: { Message: $('#Message').val()},
    success: function (data) { $('#Message').text = ''; }
});

If i debug my controller I have the Message value and going through the call and no exception, but not working. 如果我调试我的控制器,我有消息值,并通过调用,也没有异常,但不能正常工作。

Update The Request parameter is used after the Twitter authentication. 更新请求参数在Twitter身份验证后使用。 What is happening: If i call from Index for example: 发生了什么:例如,如果我从Index打电话:

if(userName != TwitterHelper._userName) 
{ 
    TwitterHelper._userName = userName; 
    TwitterHelper._accessToken = null;  
    TwitterHelper._accessTokenSecret = null; 
    TwitterHelper._userId = null; 
    TwitterHelper._screenName = null; 
}

after that: 之后:

SortedDictionary<string, string> requestTokenParams = 
    new SortedDictionary<string, string>(); 

requestTokenParams.Add("oauth_callback", HttpContext.Current.Request.Url.AbsoluteUri); 

var tokenResponse = 
    TwitterHelper.GetToken("api.twitter.com/oauth/request_token";, requestTokenParams); 

NameValueCollection qscoll = HttpUtility.ParseQueryString(tokenResponse); 

var loginUrl = "api.twitter.com/oauth/authenticate?oauth_token="; 
    + qscoll["oauth_token"];

and: 和:

//(HERE THE BROWSER SHOWS THE TWITTER LOGIN) –
HttpContext.Current.Response.Redirect(loginUrl);   

If I call Tweet from the SendTweet method the way is the same. 如果我从SendTweet方法调用Tweet,则方法相同。 But here: HttpContext.Current.Response.Redirect(loginUrl); 但是这里: HttpContext.Current.Response.Redirect(loginUrl); not shows anything, no login page. 没有显示任何内容,没有登录页面。 nothing happenin 什么都没发生

Could you please help ? 能否请你帮忙 ? Thanks in advance. 提前致谢。

You cannot Redirect from a AJAX call. 您无法从AJAX呼叫Redirect (well... basically) (嗯...基本上)

The line: 该行:

HttpContext.Current.Response.Redirect(loginUrl);

Is invalid because you are performing a asynchronous post. 无效,因为您正在执行异步发布。

Here is how it works: 下面是它的工作原理:

With: 带有:

$.ajax({
    url: "/MyController/SendTweet",
    type: "POST",
    dataType: "json",
    data: { Message: $('#Message').val()},
    success: function (data) { $('#Message').text = ''; }
});

your browser is requesting a asynchronous connection with your server and is will wait for data to arrive. 您的浏览器正在请求与服务器的异步连接,并且将等待数据到达。 If this data contains a Redirect this is not really a valid instruction in this context. 如果此数据包含Redirect则在此上下文中这实际上不是有效的指令。 It just waits for data, not for instructions. 它只是等待数据,而不是指令。

How to fix it: 解决方法:

Make your ActionResult SendTweet(string message) suitable for json 使您的ActionResult SendTweet(string message)适合json

[HttpPost]
public JsonResult SendTweet(string message)
{
    bool isAuthenticationRequired = //detect wether a user needs to login

    if (isAuthenticationRequired)
    {
        //returns indicator that login is required
        return Json(new { result = "unauthenticated" }, JsonRequestBehavior.AllowGet);
    }

    //do normal stuff

    return Json(new { result = "tweet send!" }, JsonRequestBehavior.AllowGet);
}

Then, update your ajax call to handle the result: 然后,更新您的ajax调用以处理结果:

$.ajax({
    url: "/MyController/SendTweet",
    type: "POST",
    dataType: "json",
    data: { Message: $('#Message').val()},
    success: function (data) { 

        if (data.result == "unauthenticated"){
            location.href = "an action which will redirect to the login page";
            return;
        }            

        $('#Message').text = ''; }
});

Maybe the location.href needs some additional parameters to re-post the data, but for now this seems sufficient. 也许location.href需要一些其他参数来重新发布数据,但是现在看来这已经足够了。

update 更新

I am not really familiar with the Twitter API but to redirect to the correct page you'll need a normal ActionResult , probably the one with the Ajax call on it. 我对Twitter API并不是很熟悉,但是要重定向到正确的页面,您需要一个正常的ActionResult ,可能是在其上进行Ajax调用的那个。 You can add some parameters to the url, or maybe the Twitter API provide this kind of functionality. 您可以在url中添加一些参数,或者Twitter API可以提供这种功能。

To redirect back to the correct page, take a look at: 要重定向回正确的页面,请查看:

requestTokenParams.Add("oauth_callback", 
      HttpContext.Current.Request.Url.AbsoluteUri);

The

HttpContext.Current.Request.Url.AbsoluteUri 

will send you to the SendTweet action again but since this is a json post action, it won't be able to find it. 会将您再次发送到SendTweet操作,但是由于这是json post操作,因此无法找到它。

You'll need to change 你需要改变

requestTokenParams.Add("oauth_callback", 
      HttpContext.Current.Request.Url.AbsoluteUri);

to the page with the ajax call or another page that does this and than redirect to your original page. 到具有ajax调用的页面或执行此操作的其他页面,然后重定向到您的原始页面。 You can also add some parameters to resend the tweet message. 您还可以添加一些参数以重新发送推文消息。 Something like this: 像这样:

requestTokenParams.Add("oauth_callback", 
      "someactionresult?tweetmessage=" + message);

with action: 采取行动:

public ActionResult someactionresult (string tweetmessage)
{
    //do twitter stuff
    return RedirectToAction("your original url");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM