我在jQuery AJAX POST中调用了REST服务。最初我收到网络错误:405方法不允许。但是当我在Global.asax文件中的Application_BeginRequest()中添加以下代码时,错误消失并且不调用服务。它仍会在Firefox中显示选项 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 Ajax
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]