【发布时间】:2014-05-14 23:55:09
【问题描述】:
我目前正在用 C# 创建一个网页作为学校项目。 我在文件中创建了一个 WebMethod:
默认.aspx.cs
[WebMethod]
public static string MyWebMethod()
{
return string.Format("Hello From Server");
}
以及文件中的Ajax调用:
默认.aspx
<script type="text/javascript">
function test() {
jQuery.ajax({
type: "POST",
url: "Default.aspx/MyWebMethod",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(dd, status) {
alert('Success' + JSON.stringify(dd) + " status: " + JSON.stringify(status));
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
</script>
<input type="button" value="click me" onclick="test();" />
我在“MyWebMethod()”的开头插入了一个断点,但是当我调试时,断点永远不会被命中。
我已经为这个问题坐了大约 4.5 个小时,尝试了我在 google 上找到的每个示例,即使我下载了一个完整的示例,即。带有“工作”代码的“Default.aspx”和“Default.aspx.cs”文件,我无法让它在我的解决方案中运行。
是否必须启用某些设置才能使用 JQuery、Ajax 和 WebMethods?
在我输入 JSON.stringify(dd) 之后,我得到了错误消息:
json:{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
但在寻找解决方案几个小时后,我几乎放弃了。 当我尝试一个修复程序时,它显然对其他有该错误的人有用,但它仍然对我不起作用。
有人知道怎么做吗?
感谢您的宝贵时间
【问题讨论】:
-
好像你在错误信息中有你的答案。您是否在此项目中启用了 FormsAuth 或 WindowsAuth 或其他功能?
-
我真的不知道。我刚刚在 VS2013 中新建了一个 WinForms 项目,并开始在模板中编码。它有“默认”、“关于”、“联系”页面。如何确定是否启用了 FormsAuth 或 WindowsAuth?
-
终于。我找到了解决办法!在 RouteConfig.cs 文件中,您必须取消注释行 settings.AutoRedirectMode = RedirectMode.Permanent;所以应该是: //settings.AutoRedirectMode = RedirectMode.Permanent;这为我解决了! (显然,当您是新手时,您无法回答自己的问题)
-
此外,您的响应不太可能以 JSON 字符串的形式出现。相反,它将是 XML。您应该将返回类型设置为 void,然后手动转换为 JSON(使用诸如Json.NET 之类的库)并使用
Response.Write()直接写入响应。记得设置内容类型。
标签: c# jquery asp.net ajax webmethod