在Windows项目中调用ASP.NET WebMethod

4

我该如何在Windows应用程序中从ASP.NET调用这个WebMethod

我尝试使用Web请求的POST方法,但它返回了ASP.NET页面的XML。

这是我的Web方法:

[WebMethod()]
public static string Senddata(string value)
{
    return "datareceived" + value;
}

在解决方案资源管理器中右键单击项目,选择“添加服务引用”,指定您的 Web 服务的 URL。这将在您的项目中创建一个代理类,使用它来调用您的方法。 - Habib
habib是ASP.NET项目中的一个方法。 - L202
1个回答

6

试试这个:

var theWebRequest = HttpWebRequest.Create("http://YOURURL/YOURPAGE.aspx/Senddata");
theWebRequest.Method = "POST";
theWebRequest.ContentType = "application/json; charset=utf-8";
theWebRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");

using (var writer = theWebRequest.GetRequestStream()) 
{
    string send = null;
    send = "{\"value\":\"test\"}";

    var data = Encoding.ASCII.GetBytes(send);

    writer.Write(data, 0, data.Length);
}

var theWebResponse = (HttpWebResponse)theWebRequest.GetResponse();
var theResponseStream = new StreamReader(theWebResponse.GetResponseStream());

string result = theResponseStream.ReadToEnd();

// Do something with the result
TextBox1.Text = result;

注意:您需要用实际值替换YOURURLYOURPAGE

非常感谢,它确实起作用了。但是如果我们不知道参数是“value”怎么办? - L202
据我所知,参数的名称必须匹配,什么情况下您不知道参数名称呢? - Karl Anderson
不,我不知道那是什么问题,我甚至不知道方法名。我只是被给了“somewebsite.com/somthing.aspx”。 - L202

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接