在什么情况下你得到`System.UnauthorizedAccessException`?

时间:2013-03-07 04:40:11

标签: c# windows-phone-8

我正在创建一个应用程序,在一段特定的时间间隔后,通过网络异步发送我的Windows 8 Phone的电池电量。我使用DispatcherTimer来调用在特定时间间隔后发送电池电量。

DispatcherTimer timer = new DispatcherTimer();      //Create the timer instance
        timer.Interval = TimeSpan.FromSeconds(15);          //Set the timer interval
        timer.Tick += SendAsyncRequest;                     //Call this procedure after the time ends

        timer.Start();  

我想使用POST请求发送电池电量。

void SendAsyncRequest(object sender, object e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.2.17/android_connect/add_device.php");            
        request.Method = "POST";
        request.BeginGetRequestStream(new AsyncCallback(SendBatteryLevel), request);

    }

现在,我编码发送实际请求(SendBatteryLevel)的代码的核心如下:

void SendBatteryLevel(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
        {
            string username = "CoolSops";
            string deviceId = "WindowsPhone";
            string batteryLevel = Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();
            string post_param = "username=" + username + "&device_id=" + deviceId + "&battery_level=" + batteryLevel;
            try
            {
                byte[] requestBody = System.Text.Encoding.UTF8.GetBytes(post_param);
                postStream.Write(requestBody, 0, requestBody.Length);
                SendingStatus.Text = "Battery data sent";
                postStream.Close();
            }
            catch (Exception e)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ErrorStatus.Text = e.ToString();
                });                   
                Console.WriteLine(e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace);
            }
        }           
    }

其中SendingStatusErrorStatusTextBlock。当我执行此代码时,我得到一个System.UnauthorizedAccessException。例外的细节如下:

A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary

我不明白我试图以未经授权的方式访问。有人能说出为什么会这样吗?

注意: 我在调试程序时注意到了一件有趣的事情。当从方法SendBatteryLevel调用方法SendAsyncRequest时,在从SendBatteryLevel执行几行后,控件将返回SendAsyncRequest。我试图找出确切的行数,之后控件返回SendAsyncRequest,但每次都会变化。因此,在方法完全执行之前,方法SendBatteryLevel以这种方式被调用两次或有时三次。可能是导致异常发生的原因。

2 个答案:

答案 0 :(得分:0)

使用字节数组可以更简单的方式完成 在获得响应流之前,还必须设置ContentLength

试试这个:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.2.17/android_connect/add_device.php");
request.Method = "POST";

string username = "CoolSops";
string deviceId = "WindowsPhone";
string batteryLevel = Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();
string post_param = "username=" + username + "&device_id=" + deviceId + "&battery_level=" + batteryLevel;

byte[] requestBody = System.Text.Encoding.UTF8.GetBytes(post_param);

request.ContentLength = requestBody.Length;

request.BeginGetRequestStream(
    result =>
    {
        using (var postStream = request.EndGetRequestStream(result))
        {
            postStream.Write(requestBody, 0, requestBody.Length);
            postStream.Close();
        }

        request.BeginGetResponse(
            (response) =>
            {
                // Handle response here....
            },
            null);
    },
request);

答案 1 :(得分:0)

您是否在WMAppManifest.xml中设置了所有必要的功能?

在我看来,您忘记启用ID_CAP_IDENTITY_DEVICE,ID_CAP_IDENTITY_USER或ID_CAP_NETWORKING。

你在哪里获得例外?你能否获得电池状态?