【问题标题】:Webmethod in aspx codebehind not being hit未命中 aspx 代码隐藏中的 Webmethod
【发布时间】:2018-02-16 09:20:37
【问题描述】:

我在后面的代码中有一个WebMethod,它没有被命中。我用谷歌搜索了很多,发现了很多这样的问题。我已经尝试了所有我看到的没有成功的建议。

IDE:Visual Studio 2017 框架:4.0 jQuery 版本:3.1.1 项目类型:Webforms(是的,我想念我心爱的 MVC,但这不是我的错!)

错误:

{"Message":"无效的 Web 服务调用,参数缺失值: \u0027id\u0027.","StackTrace":" 在 System.Web.Script.Services.WebServiceMethodData.CallMethod(对象 目标,IDictionary2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary2 个参数)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext 上下文、WebServiceMethodData 方法数据、IDictionary`2 rawParams)\r\n 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext 上下文,WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

正在调用的 URL:GET http://localhost:65050/Default.aspx/Save?{"id":"chkEditable","wasChecked":"on"}

当我点击两个复选框中的任何一个时,我在 Chrome 控制台上收到以下错误

获取 http://localhost:65050/Default.aspx/Save?{%22id%22:%22chkEditable%22,%22wasChecked%22:%22on%22} 500(内部服务器错误)jquery-3.1.1.min.js:4

这是我的 aspx 代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="TesteWebMethod.Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>

<script src="Scripts/jquery-3.1.1.js"></script>
<script src="Scripts/jquery-3.1.1.min.js"></script>

<script>
    $(document).ready(function () {
        $('#chkVisible').change(function () {
            Save('chkVisible', $('#chkVisible').val());
        });

        $('#chkEditable').change(function () {
            Save('chkEditable', $('#chkEditable').val());
        });
    });

    function Save(_id, _state) {
        var pageUrl = '<%= ResolveUrl("~/Default.aspx")%>';
        var _data = { "id": _id, "wasChecked": _state };

        $.ajax({
            type: "GET",
            url: pageUrl + "/Save",
            data: JSON.stringify(_data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: OnFailure
        });
    }

    function OnFailure(response) {
        console.log('falha');
        alert(response.d);
    }
    function OnSuccess(response) {
        console.log('sucesso');
        alert(response.d);
    }
</script>
</head>
<body>
<form id="form1" runat="server">
    <asp:CheckBox runat="server" AutoPostBack="false" ID="chkVisible" Text="Visivel" />
    <asp:CheckBox runat="server" AutoPostBack="false" ID="chkEditable" Text="Editavel" />
</form>

这里是代码隐藏

using System;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace TesteWebMethod
{
public partial class Default : System.Web.UI.Page
{

    [WebMethod(true)]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public static string Save(string id, string wasChecked)
    {
        bool b = wasChecked == "on";

        string data = "Id " + (b ? "was checked" : "was unchecked");

        JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

        var json = TheSerializer.Serialize(data);

        return json;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
}

我真的陷入了困境。谁能告诉我我做错了什么?

【问题讨论】:

    标签: c# jquery asp.net webforms webmethod


    【解决方案1】:

    我的回答是,您调用的方法是 GET 方法,但您传递的数据就像该方法是 POST 方法一样。 Webforms 不会从请求内容中获取参数,并且会像它们来自查询字符串一样。您在请求中包含的 JSON 数据需要通过 URL 编码到查询字符串中,或​​者该方法需要转换为 POST 方法以及 AJAX 调用。

    【讨论】:

    • 即使 JSON 数据将其转换为查询字符串,我也不相信该方法会将其正确解析为参数。
    • 感谢@Kevin Hist。我想我确实对代码做了很多更改,试图让它在某些时候迷失方向。我刚刚从 GET 更改为 POST 并且它有效。非常感谢。
    【解决方案2】:

    如果您将对象设置为data 属性,则不应将json 对象字符串化 jquery 将知道如何构建GET 请求。

    $.ajax({
        type: "GET",
        url: pageUrl + "/Save",
        data: {"id": _data.id, "wasChecked": "'" + _data.wasChecked + "'"},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: OnFailure
    });
    

    请注意,我必须整理数据,将单引号添加到 wasChecked 属性,因为That's the way ASP knows that's a string,我认为这是一个糟糕的实现。

    正如 Kevin 所说,POST 会更好。它会

    $.ajax({
        type: "POST",
        url: "WebMethodTest.aspx/Save",
        data: JSON.stringify({ "id": 2, "wasChecked": "test" }),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
    

    还有

    [WebMethod(true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string Save(string id, string wasChecked)
    {
    

    【讨论】:

    • 正如 Kevin 建议的那样,我更改为 POST 并删除注释上的 UseHttpGet = true 参数并且它起作用了。谢谢@kblok,
    猜你喜欢
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多