将WebMethods拆分为多个文件

时间:2018-12-03 22:25:04

标签: c# asp.net

我以前只有一个.aspx.cs文件,其中包含许多WebMethods。看起来像这样:

// webmethods.aspx.cs

public partial class Default : System.Web.UI.Page {
    [System.Web.Services.WebMethod]
    public static string Method1() {
    }

    [System.Web.Services.WebMethod]
    public static string Method2() {
    }

    [System.Web.Services.WebMethod]
    public static string Method3() {
    }
}

以及相应的.aspx文件,看起来像这样:

<%@ Page Language="C#" MasterPageFile="Navigation.master" AutoEventWireup="true" CodeFile="webmethods.aspx.cs" Inherits="Default" Debug="true" %>

然后我能够使用AJAX成功调用我的WebMethod。

但是webmethods.aspx.cs文件越来越大,我想将WebMethods拆分成不同的文件。所以我这样做是这样的:

webmethods.aspx.cs

// first file

namespace Foo {
    public partial class Default : System.Web.UI.Page {
        [System.Web.Services.WebMethod]
        public static string Method1() {
        }
}

webmethods2.aspx.cs

// second file

namespace Foo {
    public partial class Default : System.Web.UI.Page {
        [System.Web.Services.WebMethod]
        public static string Method2() {
        }
}

webmethods3.aspx

// third file

namespace Foo {
    public partial class Default : System.Web.UI.Page {
        [System.Web.Services.WebMethod]
        public static string Method3() {
        }
}

并将页面指令更改为Inherits="Foo.Default"

但是现在,每次我尝试通过AJAX访问其他文件中的任何WebMethod时,都会收到一个Unknown WebMethod错误。 AJAX请求仍被发送到webmethods.aspx.cs文件。

有人可以指导我做错什么吗?

1 个答案:

答案 0 :(得分:1)

WebForm编译模型允许CodeBehind使用单个partial class文件,该文件编译成单个.dll。 App_code文件夹中的所有文件在编译.aspx.aspx.cs之前的 中也编译为单个文件。因此,解决方法可能看起来像这样。

//Default.aspx
<!DOCTYPE html>
<%@ Page Language="C#" AutoEventWireup="true" Inherits="SomeApp.MyPage" %>
<%-- No CodeBehind. inherits external class--%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label runat="server" ID="lblTest"></asp:Label><br />
            <asp:Button runat="server" ID="btnTest" Text="click me" OnClick="btnTest_Click" />
        </div>
    </form>
</body>
</html>

//App_Code\MyPage.cs
namespace SomeApp
{
    public partial class MyPage : System.Web.UI.Page
    {
        //You need to declare all page controls referred by code here
        public System.Web.UI.WebControls.Label lblTest { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                lblTest.Text = "hello world from app_code";
            }
        }
    }
}

//App_code\AnotherFile.cs
namespace SomeApp
{
    public partial class MyPage : System.Web.UI.Page
    {
        protected void btnTest_Click(object sender, EventArgs e)
        {
                lblTest.Text = "hello world from btnTest_Click";

        }
    }
}

它也应与[WebMethod]一起使用。