jQuery Ajax & WCF

來源:互聯網
上載者:User

http://www.cnblogs.com/dudu/archive/2011/01/19/1939094.html

wcf contract

using System.ServiceModel;

using System.ServiceModel.Activation;

...

 

[ServiceContract]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 

public class HelloService

{

[OperationContract]

public string Say(string word)

{

return string.Format("You say \"{0}\".", word);

}

}

 這裡需要注意的是AspNetCompatibilityRequirements,如果不進行這個設定,WCF就不走ASP.NET管線,ASP.NET的上下文資訊就拿不到,比如:不加這個設定,HttpContext.Current就為null,最常用的情境就是根據HttpContext擷取使用者登入資訊,對使用者權限進行驗證。對應於這個設定,在

web.config的<system.serviceModel>中需要加上<serviceHostingEnvironment aspNetCompatibilityEnabled="true">

Web.Config

<system.serviceModel>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"></serviceHostingEnvironment>

</system.serviceModel>

*注意的地方:web.config中加了上面的設定後,所有的WCF服務實現都要設定AspNetCompatibilityRequirements屬性。

 

<system.serviceModel>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true">

        <serviceActivations>

            <add relativeAddress ="HelloService.svc" service="jQueryWCFDemo.HelloService"

                    factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/>

        </serviceActivations>

    </serviceHostingEnvironment>

</system.serviceModel>

System.ServiceModel.Activation.WebScriptServiceHostFactory

在可動態啟用服務的主機執行個體以響應傳入訊息的託管宿主環境下,能夠向該服務中自動添加 ASP.NET AJAX 終結點而無需進行配置。

 relativeAddress就是WCF服務的地址名,service就是之前建立的HelloService類名,factory是關鍵,支援ajax調用,靠的就是System.ServiceModel.Activation.WebScriptServiceHostFactory。

default.aspx

<script type="text/javascript">

    function submit_word() {

        $.ajaxSettings.url = 'HelloService.svc/Say';

        $.ajaxSettings.type = 'post';

        $.ajaxSettings.dataType = 'json';

        $.ajaxSettings.contentType = 'application/json';

        $.ajaxSettings.data = '{"word":"Hello,word"}';

        $.ajaxSettings.success = function (data) {

        alert(data.d);

    };

    $.ajax();

};

</script>

<input id="showmsg" type="button" value="show" onclick="submit_word()" />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.