C# build a websevice method that accepts POST meth

2020-05-01 06:32发布

i need a web service that accepts POST methods. An server that is accessing me is using POST method. It sends me an xml and i should response with some xml.

The other way, when i'm accessing him, i have managed with HttpWebRequest class and it works fine. It is done like:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(s.strMvrataUrl.ToString());
req.ClientCertificates.Add(cert);
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
s.AddToLog(Level.Info, "Certifikat dodan.");
byte[] bdata = null;
bdata = Encoding.UTF8.GetBytes(strRequest);
req.ContentLength = bdata.Length; 
Stream stremOut = req.GetRequestStream();
stremOut.Write(bdata, 0, bdata.Length);
stremOut.Close();
s.AddToLog(Level.Info, "Request: " + Environment.NewLine + strRequest);
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = streamIn.ReadToEnd();
streamIn.Close();

Now i would like to have a webservice that accepts POST method. Does anyone has an idea how to do this. I'm stuck here.

2条回答
The star\"
2楼-- · 2020-05-01 06:35

From http://support.microsoft.com/kb/819267:

HTTP GET and HTTP POST may be enabled by editing the Web.config file for the vroot where the Web service resides. The following configuration enables both HTTP GET and HTTP POST:

<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>
查看更多
虎瘦雄心在
3楼-- · 2020-05-01 06:40

HTTP GET and HTTP POST may be enabled in the configuration. There exists a file called webconfig file in the root where in you have to add the following setting:

<configuration>
    <system.web>
    <webServices>
            <protocols>
                <add name="HttpGet"/>
                <add name="HttpPost"/>
            </protocols>
        </webServices>
    </system.web>
</configuration>

ie inside the system.web tag.

Now in the web-service if you are intending to send an XML back you could design a struct of your wish which resembles the anticipated XML. eg: To get an XML of following type:

<?xml version="1.0" encoding="utf-8"?> 
    <Quote xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">  
        <object>Item101</object>
        <price>200</price>
    </Quote>

you have to return an object of following struct from the web-service:

public struct Quote
{
    public int price;
    public string object;
    public Quote(int pr, string obj)
    {
        price = pr;
        object = obj
    }
}

Now this can be received as response as string and then be parsed as you like.

===============================================================================

Edit I

The following is a HelloWorld WebMethod

[WebMethod]
    public string HelloWorld() {  
      return "HelloWorld";
    }

[in case of struct change the return type to corresponding struct type]

The following is a function where you can POST to a URL and also send a xml file to the webservice[Use according to your need]:

public static XmlDocument PostXMLTransaction(string URL, XmlDocument XMLDoc)
    {


        //Declare XMLResponse document
        XmlDocument XMLResponse = null;

        //Declare an HTTP-specific implementation of the WebRequest class.
        HttpWebRequest objHttpWebRequest;

        //Declare an HTTP-specific implementation of the WebResponse class
        HttpWebResponse objHttpWebResponse = null;

        //Declare a generic view of a sequence of bytes
        Stream objRequestStream = null;
        Stream objResponseStream = null;

        //Declare XMLReader
        XmlTextReader objXMLReader;

        //Creates an HttpWebRequest for the specified URL.
        objHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);

        try
        {
            //---------- Start HttpRequest

            //Set HttpWebRequest properties
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(XMLDoc.InnerXml);
            objHttpWebRequest.Method = "POST";
            objHttpWebRequest.ContentLength = bytes.Length;
            objHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";

            //Get Stream object
            objRequestStream = objHttpWebRequest.GetRequestStream();

            //Writes a sequence of bytes to the current stream
            objRequestStream.Write(bytes, 0, bytes.Length);

            //Close stream
            objRequestStream.Close();

            //---------- End HttpRequest

            //Sends the HttpWebRequest, and waits for a response.
            objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();

            //---------- Start HttpResponse
            if (objHttpWebResponse.StatusCode == HttpStatusCode.OK)
            {
                //Get response stream
                objResponseStream = objHttpWebResponse.GetResponseStream();

                //Load response stream into XMLReader
                objXMLReader = new XmlTextReader(objResponseStream);

                //Declare XMLDocument
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(objXMLReader);

                //Set XMLResponse object returned from XMLReader
                XMLResponse = xmldoc;

                //Close XMLReader
                objXMLReader.Close();
            }

            //Close HttpWebResponse
            objHttpWebResponse.Close();
        }
        catch (WebException we)
        {
            //TODO: Add custom exception handling
            throw new Exception(we.Message);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            //Close connections
            objRequestStream.Close();
            objResponseStream.Close();
            objHttpWebResponse.Close();

            //Release objects
            objXMLReader = null;
            objRequestStream = null;
            objResponseStream = null;
            objHttpWebResponse = null;
            objHttpWebRequest = null;
        }
        //Return
        return XMLResponse;
    }

And the call would be like :

 XmlDocument XMLdoc = new XmlDocument();
 XMLdoc.Load("<xml file locatopn>");
 XmlDocument response = PostXMLTransaction("<The WebService URL>", XMLdoc);
 string source = response.OuterXml;

[If this was helpful or need more help please let me know]

查看更多
登录 后发表回答