我有以下代码,如果我使用POST
. 但是,出于各种原因,我需要使用它GET
:(我添加了注释以显示我所做的 3 个简单更改,请参阅客户端脚本中的 CHANGE 1 和 CHANGE 2,以及服务器端中的 CHANGE 3脚本):
客户端:
function selectedDateTime(strDate, strHours, strMinutes) {
$.ajax({
url: 'webservice.asmx/GetCount',
//type: 'POST', // CHANGE 1 - THIS WAS POST
type: 'GET',
//data: '{"theDate": "' + strDate + ' ' + strHours + ':' + strMinutes + ':00"}', // CHANGE 2 - REMOVED THE CURLY BRACKETS
data: '"theDate": "' + strDate + ' ' + strHours + ':' + strMinutes + ':00"',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
success: function(department) {
console.log("success: " + department.d);
},
error: function(xhr, status, error) {
console.log("status message: " + status);
console.log("error message: " + error);
console.log("xhr message: " + xhr.responseText);
}
});
}
服务器端:
[WebMethod()]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] // CHANGE 3 - ADDED THIS LINE TO FORCE A GET
public double GetCount(string theDate)
{
string[] strDateAndTime = theDate.Split(' ');
string[] strStartDateParts = strDateAndTime[0].Split('/');
string[] srtStartTimeParts = strDateAndTime[1].Split(':');
int year = Int32.Parse(strStartDateParts[2]);
int month = Int32.Parse(strStartDateParts[1]);
int day = Int32.Parse(strStartDateParts[0]);
int hour = Int32.Parse(srtStartTimeParts[0]);
int min = Int32.Parse(srtStartTimeParts[1]);
int sec = Int32.Parse(srtStartTimeParts[2]);
DateTime meetingDate = new DateTime(year, month, day, hour, min, sec);
using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
{
using (command = new SqlCommand("intranet.dbo.BusinessHours", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@meeting_date", SqlDbType.DateTime).Value = meetingDate;
connection.Open();
using (reader = command.ExecuteReader())
{
reader.Read();
return (double)reader["hours"];
}
}
}
}
错误信息:
我使用谷歌浏览器的开发者工具来提取这个错误信息。
GET http://intranet/webservice.asmx/GetCount?%22theDate%22:%20%2201/07/2013%2013:00:00%22 500 (Internal Server Error)
status message: error
error message: Internal Server Error
xhr message: {"Message":"Invalid web service call, missing value for parameter: \u0027theDate\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
问题:
任何人都知道为什么会这样,当它完美地使用POST
. 我只想做同样的事情,但需要使用GET
。