使用 jsonp 實現 多網站 單點登入

來源:互聯網
上載者:User

   <script type="text/javascript"> 

      $(function () { 

            var oAUri = "@ViewBag.OAVRUri"; 

            var user = "@ViewBag.User"; 

         var pwd = "@ViewBag.PassWord"; 

           $.ajax({ 

               type: "GET", 

                url: String.format('{0}Account/AppLogOn?UserName={1}&PassWord={2}&callback=?', oAUri, user, pwd),

                cache: false,11              

  error: function () {

                  

alert("程式出錯,請聯絡管理員.");

                },

                dataType: "jsonp",

                jsonp: 'callback',

               success: function (result) {

              }

           });

       });

  </script>

 

   在MVC3.0中建立JSONP專用ActionResult

 

      代碼如下:

 

 

 

 public class JsonpResult<T> : ActionResult 

     { 

        public T Obj { get; set; }

        public string CallbackName { get; set; } 

        public JsonpResult(T obj, string callback) 

        { 

             this.Obj = obj; 

            this.CallbackName = callback;

       }

public override void ExecuteResult(ControllerContext context)

         {

             var js = new System.Web.Script.Serialization.JavaScriptSerializer();

             var jsonp = this.CallbackName + "(" + js.Serialize(this.Obj) + ")";

         context.HttpContext.Response.ContentType = "application/json";

             context.HttpContext.Response.Write(jsonp);

         }

     }

 

JsonpResult 簡單調用如下:

 

 

 public ActionResult AppLogOn(string UserName, string PassWord, string callback)

 return new JsonpResult<object>(new { success = true, rankName = rankName }, callback);

}

 

AppLogOn的action參數完全和上文中的jquery $.ajax 參數一致:

 

url: String.format('{0}Account/AppLogOn?UserName={1}&PassWord={2}&callback=?', oAUri, user, pwd)

 

小結:     Jsonp的伺服器端的原理其實就是回調一個js函數名(這裡是callback參數)將該參數傳給服務端,

接著再由伺服器端執行這個callback js函數,同時附上該js函數的參數。

比如上文的C#代碼:var jsonp = this.CallbackName + "(" + js.Serialize(this.Obj) + ")";

還有一點我們要注意的就是安全隱患問題:在使用jsonp由於涉及到跨域,需要考慮到對方網站或者對方系統的安全性問題。

應當避免安全隱患,不能濫用jsonp

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.