我在 jQuery AJAX POST 中调用了 REST 服务。最初我收到网络错误:405 Method not allowed。但是当我在 Global.asax 文件的 Application_BeginRequest() 中添加以下代码时,错误消失了,并且没有调用该服务。它仍然在 Firefox 中显示Options http 请求。为什么即使添加代码也会发生这种情况。
Application_BeginRequest()代码
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type,X-PINGOTHER Accept, x-requested-with");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
界面
[ServiceContract]
public interface IService1{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/TokenInsertion", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string UserdetailInsertion(UserInputParameters userInput);
}<br/>
服务
public string UserdetailInsertion(UserInputParameters userInput)
{
try
{
command = database.GetStoredProcCommand(DataTemplate.UspUserdetailInsertion);
database.AddInParameter(command, DataTemplate.AssociateRefId, DbType.String, userInput.AssociateRefId);
database.AddInParameter(command, DataTemplate.CpecialLoginId, DbType.String, userInput.CpecialLoginId);
database.AddInParameter(command, DataTemplate.PartnerId, DbType.String, userInput.PartnerId);
database.AddInParameter(command, DataTemplate.FirstName, DbType.String, userInput.FirstName);
database.AddInParameter(command, DataTemplate.LastName,DbType.String,userInput.LastName);
database.AddInParameter(command, DataTemplate.CreatedDate, DbType.String, userInput.CreatedDate);
database.ExecuteNonQuery(command);
return "0";
}
catch(Exception err)
{ throw err;
}
}
jQuery 阿贾克斯
var postCall = function () {
var input = {
AssociateRefId: "412", CpecialLoginId: "sdfa", PartnerId: "dfs", FirstName: "fdsf", LastName: "dfsr", Comments: "dsad", CreatedDate: "2013-02-15 15:54:10.130"
};
alert(JSON.stringify(input));
$.ajax({
type: "POST",
url: "http://localhost:45970/Service1.svc/TokenInsertion",
data: JSON.stringify(input),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (xhr, status, error) {
alert(error);
alert(status);
}
});
}<br/>
任何建议都会很有帮助。
编辑:Firefox 中的 Http 请求
--
[18:15:35.297] OPTIONS http://localhost:45970/Service1.svc/TokenInsertion [HTTP/1.1 200 OK 122ms]