简体   繁体   中英

problem with url when calling wcf service by httpWebRequest

When I call manually wcf service what should I type in url place :

HttpWebRequest httpWebRequest = WebRequest.Create(url)as HttpWebRequest;

should be there url to my svc file

http://localhost/service/LMTService.svc

or wsdl

http://localhost/service/LMTService.svc?wsdl

or url to service action ?

http://localhost/service/LMTService.svc/soap/GetSerializedSoapData

It depends on the binding of the endpoint. If using a SOAP binding (ie, basicHttpBinding , wsHttpBinding , etc), the request URI should be the endpoint address (not the service address). Also, in some SOAP versions (such as SOAP11, used in basicHttpBinding ), you need to specify the action as a HTTP header. If you're using webHttpBinding (with webHttp behavior) the address is the address of the endpoint, plus the UriTemplate (which by default is just the method name) of the operation you want to call.

The code below shows a HttpWebRequest -based request being sent to two endpoints, a one using BasicHttpBinding , one using WebHttpBinding .

public class StackOverflow_7525850
{
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        int Add(int x, int y);
    }
    public class Service : ITest
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
    public static string SendRequest(string uri, string method, string contentType, string body, Dictionary<string, string> headers)
    {
        string responseBody = null;

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
        req.Method = method;
        if (headers != null)
        {
            foreach (string headerName in headers.Keys)
            {
                req.Headers[headerName] = headers[headerName];
            }
        }
        if (!String.IsNullOrEmpty(contentType))
        {
            req.ContentType = contentType;
        }

        if (body != null)
        {
            byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
            req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
            req.GetRequestStream().Close();
        }

        HttpWebResponse resp;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch (WebException e)
        {
            resp = (HttpWebResponse)e.Response;
        }

        if (resp == null)
        {
            responseBody = null;
            Console.WriteLine("Response is null");
        }
        else
        {
            Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
            foreach (string headerName in resp.Headers.AllKeys)
            {
                Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
            }
            Console.WriteLine();
            Stream respStream = resp.GetResponseStream();
            if (respStream != null)
            {
                responseBody = new StreamReader(respStream).ReadToEnd();
                Console.WriteLine(responseBody);
            }
            else
            {
                Console.WriteLine("HttpWebResponse.GetResponseStream returned null");
            }
        }

        Console.WriteLine();
        Console.WriteLine("  *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*  ");
        Console.WriteLine();

        return responseBody;
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "basic");
        host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "web").Behaviors.Add(new WebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        string soapBody = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
  <s:Body>
    <Add xmlns=""http://tempuri.org/"">
      <x>44</x>
      <y>55</y>
    </Add>
  </s:Body>
</s:Envelope>";
        SendRequest(baseAddress + "/basic", "POST", "text/xml", soapBody, new Dictionary<string, string> { { "SOAPAction", "http://tempuri.org/ITest/Add" } });

        SendRequest(baseAddress + "/web/Add", "POST", "text/xml", "<Add xmlns=\"http://tempuri.org/\"><x>55</x><y>66</y></Add>", null);

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM