加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 无法访问aspx.cs页面上的webmethod

发布时间:2020-12-15 20:56:00 所属栏目:百科 来源:网络整理
导读:我试图用 jquery ajax调用web方法.但是,该调用返回Not Found错误.尝试直接通过URL访问该方法也会返回404错误. 我确保将EnablePageMethods =“true”参数添加到 asp:ToolkitScriptManager在母版页上. Announcements.aspx: script type="text/javascript" $(
我试图用 jquery ajax调用web方法.但是,该调用返回Not Found错误.尝试直接通过URL访问该方法也会返回404错误.

我确保将EnablePageMethods =“true”参数添加到< asp:ToolkitScriptManager>在母版页上.

Announcements.aspx:

<script type="text/javascript">
    $(function () {
        $("#CreateBtn").click(function () {
            var announce = {};
            announce["title"] = "An Announcement";
            announce["body"] = "Announcement Body";

            $.ajax({
                type: "POST",url: "Announcements.aspx/AddAnnouncement",contentType: "application/json; charset=utf-8",dataType: "json",data: JSON.stringify(announce),success: function () {
                    alert("success!");
                },error: function (x,t,e) {
                    alert(t); //alerts "error"
                    alert(e); //alerts "Not Found"
                }
            });
            return false;
        })
    });
</script>

Announcements.aspx.cs

using System.Web.Services;

namespace MyProject.ContentTools
{   
public partial class Announcements : System.Web.UI.Page
{
    protected void Page_Load(object sender,EventArgs e)
    {
    }

    [WebMethod]
    public static string AddAnnouncement(string title,string body)
    {
        var newTitle = title;
        var newBody = body;

        return "it worked!";
    }
}
}

解决方法

如果您在ASP.NET MVC项目中使用PageMethods,则可能需要忽略aspx页面的路由(以及因此基于它们的PageMethod URL).在路由注册中(通常在App_Start / RouteConfig.cs),添加以下行:

routes.Ignore("{*allaspx}",new { allaspx = @".*.aspx(/.*)?" });

这应该允许PageMethod请求通过而不受MVC路由的干扰.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读