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

本文关键字:出错 服务 授权 wcf 访问 net 异步 | 更新日期: 2023-09-27 18:13:45

我正在使用Microsoft.Data.Services.Client.Portable Windows 8 VS2013构建一个标准的odata客户端

我已经授权给项目(TMALiveData)添加了一个服务引用。现在我想检索数据,但当我这样做,我得到以下错误:DataServiceQueryException。InvalidOperationException

我看了看DataServiceQueryResult对象,状态码是: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;
        }
    }
}

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

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

mLiveData.Credentials = CredentialCache.DefaultCredentials;

或者如果你需要冒充另一个用户,你可以使用这个(显然,将字符串交换为你需要的详细信息-可能从配置中传入。

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