Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - 无法使用asp.net Web服务将Ajax标头值传递给我的Web服务方法(Not able to pass ajax headers value to my web-service method using asp.net web service)

Below is my ajax call method to the web service, I need to pass auth_key to my web service from ajax Headers, but now I am passing my auth_key using ajax data.(以下是我对Web服务的Ajax调用方法,我需要将auth_key从ajax标头传递到我的Web服务,但是现在我正在使用ajax数据传递auth_key。)

But I need to pass from 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) } }); Below is my asp.net web service(以下是我的asp.net Web服务) [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)); } I need to pass auth_key to my webservice from ajax Headers, but now i am passing my auth_key using ajax data.(我需要将auth_key从ajax标头传递到我的Web服务,但是现在我正在使用ajax数据传递auth_key。) But i need to pass from Headers.(但是我需要通过标题。) Thanks in advance(提前致谢)   ask by mohd mazhar khan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the Request object and Headers to read the request header, followed by this you can convert it into an IEnumerable object to obtain the value according to the key:(使用Request对象和Headers读取请求标头,然后可以将其转换为IEnumerable对象以根据键获取值:)

C# Code:(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 } } 在此处输入图片说明

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...