编程语言
首页 > 编程语言> > c# – 无法访问aspx.cs页面上的webmethod

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

作者:互联网

我试图用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路由的干扰.

标签:jquery,c,asp-net,webforms,webmethod
来源: https://codeday.me/bug/20190711/1433325.html