C#建立一个接受POST方法(例如HttpWebRequest方法)的websevice方法 [英] C# build a websevice method that accepts POST methods like HttpWebRequest method

查看:114
本文介绍了C#建立一个接受POST方法(例如HttpWebRequest方法)的websevice方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可以接受POST方法的Web服务.正在访问我的服务器正在使用POST方法. 它向我发送了一个xml,我应该用一些xml进行响应.

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.

相反,当我访问他时,我已经使用HttpWebRequest类进行了管理,并且工作正常.它是这样完成的:

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();

现在,我想拥有一个接受POST方法的Web服务. 有谁知道如何做到这一点.我被困在这里.

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.

推荐答案

可以在配置中启用HTTP GET和HTTP POST.根目录中存在一个名为webconfig文件的文件,您必须在其中添加以下设置:

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>

即位于system.web标记内.

ie inside the system.web tag.

现在,如果您打算将XML发送回Web服务,则可以设计一个类似于预期XML的愿望结构. 例如:要获取以下类型的XML:

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>

您必须从Web服务返回以下结构的对象:

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.

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

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

以下是HelloWorld WebMethod

The following is a HelloWorld WebMethod

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

[如果将结构更改为返回类型,则返回相应的结构类型]

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

以下是一个函数,您可以在其中发布到URL,也可以将xml文件发送到Web服务[根据需要使用]:

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;
    }

呼叫将是:

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

[如果有帮助或需要更多帮助,请告诉我]

这篇关于C#建立一个接受POST方法(例如HttpWebRequest方法)的websevice方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆