Wcf Restful Service提供方法不允许或错误请求

时间:2015-11-13 14:34:08

标签: c# wcf wcf-rest

我的服务已定义:

[ServiceContract(ProtectionLevel = ProtectionLevel.None)]
[XmlSerializerFormat]
public interface IMSMService
{

    [OperationContract(IsOneWay = false)]
    [WebInvoke(Method = "POST", UriTemplate = "GetProducts", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    ProductsResponse GetProducts(ProductsRequest request);

}

,方法标题采用以下形式:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MSMService : IMSMService
{.....

我运行该服务,然后在客户端应用程序中,我对wcf进程进行了服务引用。在我的客户测试项目中,我有以下测试。

 [Test]
    public void CallWCFRestful()
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(ProductsRequest));

        MemoryStream stream = new MemoryStream();

        xmlSerializer.Serialize(stream,_productsRequest);

        string data = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
       string link = "http://localhost/WcfService/GetProducts";
       var request = (HttpWebRequest)WebRequest.Create(new Uri(link));

        request.ContentType = "application/soap+xml; charset=utf-8";
        request.Method = "POST";
        request.ContentLength = data.Length;
        request.KeepAlive = true;

        using (var requestStream = request.GetRequestStream())
        {

            var writer = new StreamWriter(requestStream);

            writer.Write(data);

            writer.Flush();

        }

        using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
        {

            using (var responseStream = resp.GetResponseStream())
            {

                var reader = new StreamReader(responseStream);

                var result = reader.ReadToEnd();

            }

        }
    }

在Code中,当我运行服务时,在尝试使用错误的请求错误设置'resp'时出错。如果我按住Ctrl +单击http://localhost/WcfService,则表明服务正在运行。如果我按照我的代码行包含方法,那么我接收方法不允许(我希望这是因为我没有传递对象)。我做错了什么。

1 个答案:

答案 0 :(得分:0)

由于这是一个WCF REST服务,因此内容类型不能是SOAP。它需要是application / xml。尝试更改内容类型并再次测试。这可能是原因=,或者至少是其中一个原因。

更改如下:

request.ContentType = "application/xml; charset=utf-8";