无法使用 asp.net 网络服务将 ajax headers 值传递给我的 web-service 方法

Not able to pass ajax headers value to my web-service method using asp.net web service

下面是我的 ajax 调用网络服务的方法,我需要从 ajax Headers 传递 auth_key 到我的网络服务,但现在我正在传递我的 auth_key 使用 ajax 数据。但是我需要从 Headers.

    $.ajax({
    type: "GET",
    url: base_url + "ongoingtrainingdetails",
    data: {'Username':window.localStorage.getItem('auth_key')}, //'7EF1590A-29A3-4DD5-885A-5C773480AF91'},
    timeout: 60000,
    dataType: "json",
    headers: {
        "X-Api-Key": localStorage.getItem("auth_key")
    },
    Complete: function(xhr) {
        xhr.getResponseHeader("Accept", "json");
    },
    success: function(res) {
        console.log(res);


     if (res.status === 7) {
     var html = "<div class='col-xs-12 main-area'>   <div class='no-traing-block'>        <p clas" +
                    "s='no-traing-block-icon'>            <img src='images/no-training-icon.png'><br>" +
                    " No ongoing training available        </p>    </div></div>";
                $("#home_page_content").html(html);
                 SpinnerPlugin.activityStop();

      }else if (res.status === 0) {
             console.log(res);
            var a = CryptoJS.AES.encrypt(JSON.stringify(res), localStorage.getItem("auth_key"), 256);
            localStorage.setItem("res", a);

            var d = CryptoJS.AES.decrypt(localStorage.getItem("res"), localStorage.getItem("auth_key")).toString(CryptoJS.enc.Utf8);
            var res = JSON.parse(d);
            //var res = d;
            console.log(res);
            console.log(res.data.dStartdate);

            var iTrainingId = res.data.iTrainingId;
            // localStorage.setItem("dStartdate", res.data.dStartdate);
            // localStorage.setItem("dEnddate", res.data.dEnddate);
            console.log(res.data.eTrainingMode);

            if (res.status === 0) {
                insertDB(res);
                var html = "";
               // if (true) {
                if (res.data.eTrainingMode == "Pending") {
                    html += "<div class='col-xs-12 main-area' >     <div class='index-data'>        <div clas" +
                        "s='index-data-row'>           <h1><img src='images/current-training-icon.png'>Cu" +
                        "rrent Training</h1>           <p><img src='images/programname-icon.png'>Enrollme" +
                        "nt ID</p>           <h2 id='program_name_homepage'>" + res.data.vUniqueCode + "</h2>           <p><img src='images/programname-icon.png'>Program Name</p>      " +
                        "     <h2 id='program_name_homepage'>" + res.data.vTrainingName + "</h2>           <p><img src='images/krc-name-icon.png'>KRC Name</p>           <h" +
                        "3 id='program_address_homepage'>" + res.data.KRC_name + "</h3>           <p><img src='images/map-1.png'>Location</p>           <h3 id='pr" +
                        "ogram_address_homepage'>" + res.data.vDistrict + "," + res.data.vState + "</h3>           <p><img src='images/date-icon.png'>From Date</p>           <h4 i" +
                        "d='program_start_homepage'>" + getFormattedDate(res.data.dStartdate) + "</h4>           <p><img src='images/date-icon.png'>To Date</p>           <h4 id=" +
                        "'program_end_homepage'>" + getFormattedDate(res.data.dEnddate) + "</h4>        </div>        <p class='trainer-font'><img src='images/master-train" +
                        "er-icon.png'>Master Trainer</p>        <div class='trainer-row' id='master_train" +
                        "er'><img src='images/profile-img.png'>" + res.data.vName + "<span id='start_training_home' data-training='" + res.data.iTrainingId + "'>START</span></div>        <div id='otherTrainers'></div>    </div></div>";
                    $("#home_page_content").html(html);
                    SpinnerPlugin.activityStop();
                    SpinnerPlugin.activityStop();
                } else if (res.data.eTrainingMode == "Online") {
                    SpinnerPlugin.activityStop();
                    getCurrentRunningBatch();
                } else if (res.data.eTrainingMode == "Offline") {
                    SpinnerPlugin.activityStop();
                    getCurrentRunningBatch();
                }

            } else {
                debugger;
                alert("reached 4");
                var html = "<div class='col-xs-12 main-area'>   <div class='no-traing-block'>        <p clas" +
                    "s='no-traing-block-icon'>            <img src='images/no-training-icon.png'><br>" +
                    " No ongoing training available        </p>    </div></div>";
                $("#home_page_content").html(html);

                SpinnerPlugin.activityStop();
                //navigator.notification.alert(res.message); console.log(res.message);
            }
        } else {
            SpinnerPlugin.activityStop();
            //navigator.notification.alert(res.message);
        }
    },
    error: function(xhr, status, err) {
        console.log(xhr +"hi");
        console.log(status + "helo");
        console.log(err+"error is");
        ErrorHandler(xhr, status, err)
    }
});

下面是我的 asp.net 网络服务

   [WebMethod(EnableSession = false)]
  [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]//Specify return format.
  public void ongoingtrainingdetails(string UserName)
 {

 //Context.Response.Write(UserName);


 List<Response> listbatch = new List<Response>();
 using (SqlConnection con = new SqlConnection(strConn))
 {
     SqlCommand cmd = new SqlCommand("App_Service", con);
     try
     {

         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@Paravalue", "2");
         cmd.Parameters.AddWithValue("@value", UserName);
         cmd.Parameters.AddWithValue("@value1", "");
         cmd.Parameters.AddWithValue("@value2", "0");
         cmd.Parameters.AddWithValue("@value3", "0");
         con.Open();
         SqlDataReader rdr = cmd.ExecuteReader();
         while (rdr.Read())
         {
             Response res = new Response();
             res.status = 0;
             res.message = "Welcome To u";
            // res.auth_key = rdr["auth_key"].ToString();
             Data batch = new Data();
             {
                 batch.vUniqueCode = rdr["vUniqueCode"].ToString();
                 batch.vTrainingName = rdr["BatchTitle"].ToString();
                 batch.dStartdate = rdr["BatchStarDate"].ToString( );
                 batch.dEnddate = rdr["BatchEndDate"].ToString();
                 batch.vDistrict = rdr["CityName"].ToString();
                 batch.vState = rdr["StateName"].ToString();
                 batch.Address = rdr["Address"].ToString();
                 batch.TrainerId = int.Parse(rdr["TrainerId"].ToString());
                 batch.eTrainingMode =rdr["eTrainingMode"].ToString();

                 batch.vName = rdr["vName"].ToString();
                 batch.iTrainingId = int.Parse(rdr["vUniqueCode"].ToString());
                 res.data = batch;
             };
             listbatch.Add(res);
         }
         this.Context.Response.ContentType = "application/json; charset=utf-8";
         //string JSONResult = JsonConvert.SerializeObject(listbatch);
         JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 867530900 };
         string JSONResult = js.Serialize(listbatch);
         string FinalJsonstring1 = JSONResult.Replace("[", "");
         string FinalJsonstring2 = FinalJsonstring1.Replace("]", "");
         Context.Response.Write(FinalJsonstring2);
         //string aukey=HttpContext.Current.Request.Headers.Get("auth_key");
         cmd.Dispose();
         con.Close();
         con.Dispose();
     }
     catch (Exception ex)
     {
         ExceptionLogging.SendErrorToText(ex);
         status = ex.GetHashCode().ToString();
         message = ex.Message.ToString();
         throw new SoapException(ex.Message, SoapException.ServerFaultCode, Context.Request.Url.AbsoluteUri);
     }
     finally
     {
         cmd.Dispose();
         con.Close();
         con.Dispose();
     }
 }
 //JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 867530900 };
 //Context.Response.Write(js.Serialize(listbatch));
 }

我需要将 auth_key 从 ajax Headers 传递到我的网络服务,但现在我正在使用 ajax 数据传递我的 auth_key。但我需要从 Headers 传递。提前致谢

使用 Request 对象和 Headers 读取请求头,然后将其转换为 IEnumerable对象根据key获取值:

C#代码:

[WebMethod(EnableSession = false)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void ongoingtrainingdetails(string UserName)
{

    SqlCommand cmd = new SqlCommand("App_Service", con);

    try
    {
        var request = HttpContext.Current.Request;

        IEnumerable<string> headers = request.Headers.GetValues("X-Api-Key");

        var value = headers.FirstOrDefault();

        // Code
    }
    catch (Exception ex)
    {
        //Code
    }
    finally
    {
       //Code
    }

}