无法使用 asp.net Web 服务将 ajax 标头值传递给我的 Web 服务方法

Posted

技术标签:

【中文标题】无法使用 asp.net Web 服务将 ajax 标头值传递给我的 Web 服务方法【英文标题】:Not able to pass ajax headers value to my web-service method using asp.net web service 【发布时间】:2020-03-24 17:20:09 【问题描述】:

下面是我对 Web 服务的 ajax 调用方法,我需要从 ajax Headers 将 auth_key 传递给我的 Web 服务,但现在我正在使用 ajax 数据传递我的 auth_key。但我需要从 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 传递给我的 web 服务,但现在我正在使用 ajax 数据传递我的 auth_key。但我需要从标头传递。提前致谢

【问题讨论】:

【参考方案1】:

使用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
    


【讨论】:

以上是关于无法使用 asp.net Web 服务将 ajax 标头值传递给我的 Web 服务方法的主要内容,如果未能解决你的问题,请参考以下文章

尽管有 web.config 条目,但带有 ASP.NET WCF 服务的 jQuery AJAX CORS 无法正常工作

无法从 jQuery 使用 ASP.NET Web 服务

使用 ajax asp.net 调用 Web 服务

Asp.net Webservice - 使用 jquery AJAX 安全调用 Web 服务

如何使用 ajax 从跨域调用 asp.net Web 服务

无法使用 AFNetworking 将 iOS 连接到 asp.net webservices