2012-10-03 31 views
1

我遇到了示例中的簡單C#Web服務問題。 這是我的服務器端代碼:異步Web服務中的EndInvoke返回無用值

public delegate string LengthyProcedureAsyncStub(int milliseconds); 

    public class MyState 
    { 
     public string text; 
     public object previousState; 
     public LengthyProcedureAsyncStub asyncStub; 
    } 

    [WebMethod] 
    public IAsyncResult BeginLengthyProcedure(int milliseconds, AsyncCallback cb, object s) 
    { 
     LengthyProcedureAsyncStub stub = new LengthyProcedureAsyncStub(LengthyProcedure); 
     MyState ms = new MyState(); 
     ms.previousState = s; 
     ms.asyncStub = stub; 
     return stub.BeginInvoke(milliseconds, cb, ms); 
    } 

    public string LengthyProcedure(int milliseconds) 
    { 
     System.Threading.Thread.Sleep(milliseconds); 
     return "Success"; 
    } 

    [WebMethod] 
    public string EndLengthyProcedure(IAsyncResult call) 
    { 
     MyState ms = (MyState)call.AsyncState; 
     string result = ms.asyncStub.EndInvoke(call); 
     return result;//ms.text; 
    } 

我使用該服務從客戶端,像這樣:

private void button1_Click(object sender, EventArgs e) 
    { 

     Waiter(5000); 

    } 

    private void Waiter(int milliseconds) 
    { 
     asyncProcessor.Service1SoapClient sendReference; 
     sendReference = new asyncProcessor.Service1SoapClient(); 
     sendReference.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; 
     sendReference.BeginLengthyProcedure(milliseconds, ServiceCallBack, null); 

    } 

    private void ServiceCallBack(IAsyncResult result) 
    { 
     string strResult = result.ToString(); 
    } 

的問題是,客戶端變量strResult應該有「Sucess」,因爲它的價值,而不是它有這樣的:「System.ServiceModel.Channels.ServiceChannel + SendAsyncResult」。 我在做什麼錯誤或忽略?

在此先感謝您的來回時間:)

+1

歡迎來到Stack Overflow!請注意,標籤獨立。組合單個標籤不會給他們額外的含義。例如,結合'web'和'service'並不意味着你在談論Web服務。 – Charles

+0

@Charles 謝謝您澄清查爾斯。我會繼續關注未來。 – user1417947

回答

0

你要通過sendReference而不是null

private void Waiter(int milliseconds) 
{ 
    asyncProcessor.Service1SoapClient sendReference; 
    sendReference = new asyncProcessor.Service1SoapClient(); 
    sendReference.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; 
    sendReference.BeginLengthyProcedure(milliseconds, ServiceCallBack, sendReference); 

} 

private void ServiceCallBack(IAsyncResult result) 
{ 
    asyncProcessor.Service1SoapClient sendReference = result.AsyncState as asyncProcessor.Service1SoapClient; 
    string strResult = sendReference.EndLengthyProcedure(result); 
} 
+0

謝謝你的回答Grzegorz。這解決了這個問題。進行更改後,我還有一個小細節。我收到錯誤: 「HTTP請求未經授權,客戶端身份驗證方案爲'Anonymous'。從服務器收到的身份驗證頭是'Negotiate,NTLM'」,可以通過啓用匿名訪問在IIS中解決,但這違反了我們的政策所以我更改了app.config中的另一個綁定,以使用TransportCredentialOnly並且效果很好。再次感謝。 – user1417947