asp.net
  • wcf
  • 2011-10-17 213 views 2 likes 
    2

    请查看下面给出的代码。调试到达request.GetResponse()语句时,该错误已被抛出。远程服务器返回错误:(400)使用WCF服务时请求错误

    Uri uri = new Uri(address); 
    string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>"; 
    
    data.Replace("'", "\""); 
    
    // Create a byte array of the data we want to send 
    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data); 
    
    if (uri.Scheme == Uri.UriSchemeHttps) 
    { 
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); 
        request.Method = "POST";// WebRequestMethods.Http.Post; 
        request.ContentLength = byteData.Length; 
        request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8"; 
        //request.ContentType = "application/x-www-form-urlencoded"; 
    
        //Stream requestStream = request.GetRequestStream(); 
        using (Stream writer = request.GetRequestStream()) 
        { 
         writer.Write(byteData, 0, byteData.Length); 
        } 
        //writer.Close(); 
    
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
        { 
         // Get the response stream 
         StreamReader reader = new StreamReader(response.GetResponseStream()); 
         string tmp = reader.ReadToEnd(); 
         Response.Close(); 
         Response.Write(tmp); 
        } 
    
    +4

    请问为什么神圣地球上您使用HttpWebRequest和手动伪造的HTTP请求,消耗WCF服务,而不是使用自动生成的强类型的代理(使用添加服务引用功能生成的一个在Visual Studio中)? –

    +0

    这段代码有很多问题。 1)不使用“添加服务引用”,而是重新发明轮子 - 糟糕。 2)并非所有的IDisposable对象都处于“使用”块中。比如,StreamReader需要这个。 3)通过字符串操作而不是通过LINQ to XML或其他XML API来创建XML。 –

    回答

    1

    我会仔细检查网址。如果URL在客户端看起来不错,我建议查看服务器上的访问日志以查看正在访问的URL。 4xx错误意味着没有找到资源。如果端点是正确的,但请求已被取消,您将得到一个5xx错误代码。 (假设你的服务器端框架使用标准的HTTP响应代码)。

    +0

    该服务位于另一个服务器中(https://serverurl/servicename/classname.svc) –

    +0

    有您的请求时出现错误。您是否尝试使用卷曲工具发射完全相同的请求?如果不是,我建议使用curl或类似的工具来首先弄清楚干净的请求是什么样的,然后在客户端应用程序中模拟相同的请求。最有可能的是,你的请求头文件已经打包。 –

    1

    如前所述,您应该使用“添加服务引用”从.NET客户端访问WCF服务。但是,如果您正在模拟尝试从非.NET客户端进行连接,则您的soap信封缺少标题信息。

    <s:Header> 
        <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none"> 
    specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute) 
        </Action> 
    </s:Header> 
    
    相关问题