想要仅使用html页面来创建一个简单的web服务/ api到aspx

时间:2018-04-12 18:05:15

标签: asp.net vb.net rest web-services wcf

我有一个简单的html页面,用户输入一个FunctionName及其参数并提交调用(参见HTML文本):.....

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form action="process.aspx" method="post">
    GMailFunction <input type="text" id="GMFunction" name="GMFunction"   
    GMailParameters<input type="text" id="GMFParameters" name="GMFParameters"  
  <input type="submit" value="Submit" />
</form>
</body>
</html>

此调用由名为process.aspx的ASPX页面回答,该页面仅包含以下代码:

Partial Class _Default
Inherits System.Web.UI.Page

Private Sub _Default_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dim GMFunction As String = Request.Form("GMFunction")
    Dim GMFParameters As String = Request.Form("GMFParameters")
    Response.Write(GMFunction)
    Response.Write(<br></br>)
    Response.Write(GMFParameters)
    Response.Write(<br></br>)
    Response.Write("Hello World FROM DEFAULT CLASS")
End Sub
End Class

问题:
  1.在html代码中,当我将方法更改为GET时,请求不会被处理。我的代码需要更改什么?
  2.如果我想绕过HTML页面直接从让我们说一个Windows程序到达aspx(比如web api),那么如何为GET和POST创建URL?

1 个答案:

答案 0 :(得分:0)

您使用action="process.aspx" method="post"调用Process.aspx页面,代码隐藏中的事件将以特定(已知)顺序触发。 Partial Class Process不是其中之一,也不是事件。你必须自己打电话。最简单的方法是在load事件中调用它,但那么你将如何将响应返回到你的html页面?你需要编写一些javascript代码(jQuery是一个很好的库),也许有些ajax,ajax可能会更好。您所做的很多事情也取决于您的开发平台,我假设您正在使用Visual Studios,如果是,那么什么版本?

将您的函数更改为web方法(有关stackoverflow的大量示例),然后使用ajax调用webmethod:

<script src="scripts/jquery.js" type="text/javascript"></script>

<script type="text/javascript">

    $.ajax({
        type: "POST",
        url: "process.aspx/SomeWebMethod",
        // the parameter names must match webmethod parameter names exactly
        data: JSON.stringify({ parameter1Value: 'somedata', parameter2Value: 'moredata' }), 
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        traditional: true
        success: function (response) {
            alert("Data sucessfully transmited.");
            // do stuff here on success like retrieve the data
            // easiest way is to set a public variable in the code behind with the data you want to retrieve
            // and then set a label's value to the data or some such.
            var thedata = '<%=PublicVariableInCodeBehind%>';
            // This assumes aspx page is calling the webmethod
            $("#<%=SomeLabelName.ClientID%>").val(thedata);
            // To set a html label with the data
            // $('#labelName').text(thedata);
            // You can also  do things like add a row and cells to a table and display the data that way, whatever you want to do.
        },
        error: function (response) {
            alert("Error = " + response.responseText);
        }
    });


</script>