简体   繁体   中英

Return the result as partial view from asp.net MVC 4 controller

I am trying to access Linked in profile data in my asp.net mvc 4 application. I have created a link to post data to linked in like this

Get LinkedIn Profile

Then in this action method, I am creating url to post to linked in, passing return url

 [AllowAnonymous]
        public ActionResult LinkedIn()
        {
            string APIKey = ConfigurationManager.AppSettings["LiApiKey"];
            string SecretKey = ConfigurationManager.AppSettings["LiSecretKey"];

            _oathClient.RegisterClient(APIKey, SecretKey);


            string redirectURL = _oathClient.Authenticate(new Uri("http://127.0.0.1:81/Account/LinkedInAuthorized"));
            return Redirect(redirectURL);

}

when user returns to this call back function, I make API call to get access token:

  [AllowAnonymous]
        public ActionResult LinkedInAuthorized(string code, string state)
        {          
            string returnVal = _oathClient.LinkedInShare(new Uri("http://127.0.0.1:81/Account/LinkedInAuthorized"), code);

 return PartialView("LinkedInProfileInfo", returnVal);
}


 public string LinkedInShare(Uri redirectUri, string authorizationCode)
        {
            var accessCodeUri =
                string.Format(
                    "https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code={0}&redirect_uri={1}&client_id={2}&client_secret={3}",
                    authorizationCode,
                    redirectUri.AbsoluteUri,
                    linkedInApiKey,
                    linkedInSecretKey);

            return LinkedInWebRequest(accessCodeUri);
        }

where LinkedInWebRequest makes another API call to get Linked in data etc.

My problem is that I want to return partial view from LinkedInAuthorized but when LinkedInProfileInfo loads, it opens in full page, replacing contents of the main view.

I tried using child only attribute but that is not acceptable as call back function. I tried using renderpartial and render action, html.partial, but all of them replace the contents of main view.

How can I return the result of Oauth 2.0 CallBack function as partial view ?

I couldn't find the libraries you've used to authenticate against linkedin. So I went ahead and did something myself. The same principle would apply in your case. Of course, you might need to adapt your design to the idea.

For the purpose of the demonstrated I have somehow bypassed the traditional login process (checking against the db, etc); the oauth page is a simple form with accepts a callback url; it has a textbox (to collect the username typed into it) and a submit button which redirects to a page in the calle (App1).

Note the javascript in the "client" web application.

App1 - the client web application


WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.App1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>OAuth</title>

    <link href="Content/bootstrap.min.css" rel="stylesheet" type="text/css" />

</head>
<body>
    <div style="margin-left: 15px">
        <h2>Mock Oauth with ASP.NET Webforms</h2>
        <p>Although this example is based on ASP.NET Webforms the principle is the same for an ASP.NET MVC web application</p>
        <p>Button <strong>Authenticate Me</strong> will pop up an iframe in this page which navigates to your authentication provider</p>
        <p>Right click and view the page source to understand the javascript required for the authentication to happen</p>
        <form id="form1" runat="server">
            <div>
                <input id="btnauth" type="button" value="Authenticate Me" class="btn btn-default" />
            </div>
        </form>
        <div id="result" class="well">
            Hello Guest!
        </div>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">Authenticating...</h4>
                </div>
                <div class="modal-body">
                    <iframe id="auth-iframe" style="width:100%; border:none" src="about:blank"></iframe>
                </div>
                <div class="modal-footer">
                    &nbsp;                    
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="Scripts/jquery-2.0.3.min.js"></script>
    <script type="text/javascript" src="Scripts/bootstrap.min.js"></script>
    <script>
        var auth_service = 'http://localhost:36535/authenticate.aspx';
        var call_back = '<%= new System.Uri(Page.Request.Url, "/OauthCallback.aspx").AbsoluteUri %>';
        function oAuthBegin() {
            $('#myModal').modal('show');
            $('#auth-iframe').attr('src',
                auth_service + '?callback=' + encodeURI(call_back));
        }

        function oAuthEnd(username) {
            $('#myModal').modal('hide');
            $('#btnauth').attr('disabled', 'disabled');
            $('#result').html("Hello " + username);
        }

        $(function () {
            $('#btnauth').click(function () {
                oAuthBegin();
            });
        });
    </script>
</body>
</html>

Notice there is an iframe. The iframe will redirect to oauth service. The oauth service will redirect to the provided callback url. This wiring is done in javascript itself.

OAuthCallback.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OauthCallback.aspx.cs" Inherits="WebApp.App1.OauthCallback" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>OAuth Callback</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>Patience, you are authenticated as of now...redirecting...</p>
    </div>
    </form>
    <script type="text/javascript" src="Scripts/jquery-2.0.3.min.js"></script>
    <script>
        $(function () {
            var username = '<%= Request.QueryString["username"] %>';
            setTimeout(function () {
                parent.window.oAuthEnd(username);
            }, 5000);
        });
    </script>
</body>
</html>

Notice in the above page that I call the oAuthEnd js function; this executes on our parent page.

App2 - the oauth service mock


authenticate.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="authenticate.aspx.cs" Inherits="WebApp.App2.authenticate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter User Name: <asp:TextBox ID="tbxUserName" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="btnauth" runat="server" Text="Authenticate" OnClick="btnauth_Click" />
    </div>
    </form>
</body>
</html>

authenticate.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApp.App2
{
    public partial class authenticate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnauth_Click(object sender, EventArgs e)
        {
            var url = string.Format("{0}?username={1}", Request.QueryString[0], Server.UrlEncode(tbxUserName.Text));
            Response.Redirect(url);
        }
    }
}

Will update this answer with the link to a downloadable solution once I upload it somewhere...

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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