首页 > 解决方案 > HttpContext.Current.Session 在调用 Web 方法时抛出了 System.NullReferenceException 类型的异常

问题描述

我正在尝试在 Ajax 中调用 webmethod,并且我想通过会话获取当前登录用户 ID。HttpContext.Current.Session 怎么抛出 System.NullReferenceException,我怎么能得到 HttpContext.Current.Session。这是我的代码。

             function GetReportID() {
                indicatorsIds = getSelectedIndicatorsIDs();
                locationsIds = getSelectedLocationsIDs();
                $.ajax({
                    type: "POST",
                    url: '<%= ResolveUrl("ChartEdit.aspx/GetIDForDownloadExcel") %>',
                    data: JSON.stringify({ ind: indicatorsIds, loc: locationsIds }),
                    contentType: "application/json",
                    dataType: "json",
                    success: function (data) {
                        //alert('Data: ' + data);
                        var data = JSON.parse(data.d)
                        console.log(data);
                        console.log(data.ClientID);
                    },
                    error: function (xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(err.Message);
                    }
                });
            }

这是 WebMethod 和代码。

 public static string GetIDForDownloadExcel(string[] ind, string[] loc)
    {
        ChartEdit cd = new ChartEdit();

        List<string> locationIDs = new List<string>(1024);
        List<string> indicatorIDs = new List<string>(1024);

        Guid clientID = Guid.NewGuid();

        excelData.Ready = 0;

        store.Add(clientID, excelData);

        Thread thread = new Thread(() => cd.ExportToExcelDict(locationIDs, indicatorIDs,clientID));
        thread.Start();

        return JsonConvert.SerializeObject(new { ClientID = clientID, filename = "ExportToExcel" });
    }

当它运行到以下代码时,会抛出 NullReference Exception。

     public static int GetCurrentUserId()
        {
            return Convert.ToInt32(HttpContext.Current.Session[FujiXerox.Common.Constants.KEY_NAME_CURRENT_USER_ID]);
        }

标签: c#asp.netsessionwebmethod

解决方案


推荐阅读