【问题标题】:Wcf Restful Service gives Method Not allowed or Bad RequestWcf Restful Service 给出 Method Not allowed 或 Bad Request
【发布时间】:2016-02-15 04:10:03
【问题描述】:

我的服务已定义:

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

            }

        }
    }

在我运行服务的代码中,尝试设置“resp”时出现错误请求错误。如果我按 ctrl+单击http://localhost/WcfService,则显示服务正在运行。如果我按照我的代码行包含该方法,那么我会收到 Method not allowed (我希望这是因为我没有传递对象)。我做错了什么。

【问题讨论】:

  • 链接是否有效。我的意思是服务端点?

标签: c# wcf wcf-rest


【解决方案1】:

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

如下更改:

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

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 2020-02-16
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2016-01-13
    • 2016-09-07
    相关资源
    最近更新 更多