远程服务器在使用WCF服务时返回错误:(400)错误请求

时间:2011-10-17 22:14:38

标签: asp.net wcf

请查看下面给出的代码。当调试到达request.GetResponse()语句时,错误已被抛出。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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>