在c#.net中异步访问wcf服务时出错:未经授权

时间:2014-07-21 10:16:56

标签: c# xamarin wcf-data-services

我正在使用以下内容构建标准odata客户端:Microsoft.Data.Services.Client.Portable Windows 8 VS2013

我已经通过授权为项目添加了服务引用(TMALiveData)。现在我想检索数据,但是当我这样做时,我收到以下错误:DataServiceQueryException.InvalidOperationException

我查看了状态代码为DataServiceQueryResult的{​​{1}}对象:System.Net.HttpStatusCode.Unauthorized

当我添加引用时,它询问了我的凭据,因此我假设这将随每个查询一起发送,但显然不是。如何在DataServiceQuery对象中添加凭据(密码和用户名)?以下是我目前的代码:

  public class testLSCon
  {
     static string mResult;

     public static string result { get { return mResult; } }

     public static void testREADLiveConnection()
     {
        Uri tmaLiveDataRoot = new Uri("https://xxx.azurewebsites.net/xxx.svc/");
        TMLiveData.TMALiveData mLiveData = new TMLiveData.TMALiveData(tmaLiveDataRoot);

        mResult = null;

        DataServiceQuery<TMLiveData.JobType> query = (DataServiceQuery<TMLiveData.JobType>)mLiveData.JobTypes.Where(c => c.IsActive == true);
        mResult = "Trying to READ the data";
        try
        {
            query.BeginExecute(OnQueryComplete, query);
        }
        catch (Exception ex)
        {
            mResult = "Error on beginExecute: " + ex.Message;
        }
     }

     private static void OnQueryComplete(IAsyncResult result)
     {
        DataServiceQuery<TMLiveData.JobType> query = (DataServiceQuery<TMLiveData.JobType>) result.AsyncState; 

        mResult = "Done!";
        try
        {
            foreach (TMLiveData.JobType jobType in query.EndExecute(result))
            {
                mResult += jobType.JobType1 + ",";
            }
        }
        catch (DataServiceClientException ex)
        {
            mResult = "Error looping for items: (DataServiceClientException)" + ex.Message;
        }
        catch (DataServiceQueryException ex2)
        {
            mResult = "Error looping for items: (DataServiceQueryException)" ;
        }
        catch (Exception ex3)
        {
            mResult = "Error looping for items: (general exception)" + ex3.Message;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以将其设置为当前用户的凭据(因此客户端正在运行的用户的凭据)

mLiveData.Credentials = CredentialCache.DefaultCredentials;

或者如果你需要模仿另一个用户,你可以使用它(显然交换字符串以获取你需要的详细信息 - 也许可以从config传入。

mLiveData.Credentials = new System.Net.NetworkCredential("UserName", "Password", "Domain");