call asp.net webmethod in windows project

喜夏-厌秋 提交于 2019-12-30 10:06:21

问题


How do I call this WebMethod in ASP.NET from a Windows application?

I have tried using web request post method, but it is returning the XML of the ASP.NET page.

Here is my web method:

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

回答1:


Try this:

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;

Note: You need to replace YOURURL and YOURPAGE with real values.



来源:https://stackoverflow.com/questions/19597291/call-asp-net-webmethod-in-windows-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!