在WCF REST服务中插入数据显示错误:远程服务器返回错误:(404)Not Found

时间:2014-04-18 16:02:28

标签: wcf rest

我创建了两种方法,一种是获取,另一种是创建

为获取数据工作正常,但当我尝试发布数据时显示错误,如Method not Found(404)

守则如下。

合同方法:

public interface IContactPositionService    {     
   [OperationContract]       
 [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "GET",RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetContactPositionList")]    
    List<ContactPosition> GetContactPositionList(); 
[OperationContract]      
  [WebInvoke(Method = "PUT", BodyStyle = WebMessageBodyStyle.WrappedRequest,RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "AddContactPosition")]       
 int AddContactPosition(ContactPosition position);}

对应的Serivice课程就像:

public class ContactPositionService : IContactPositionService
    {
  public List<ContactPosition> GetContactPositionList()
        {
            DataSet ds = clsObj.GetContactPositionsList();
            return ConverterHelper.Convert<ContactPosition>(ds.Tables[0]);
        }

 public int AddContactPosition(ContactPosition position)
        {
          //  throw new System.NotImplementedException();
        }

在Web.config文件中,我将端点配置为:

<services>
      <service name="VirtusMobileService.ContactPositionService" behaviorConfiguration="VMS.Position.ServiceBehaviour">
        <endpoint address="" behaviorConfiguration="VMS.Position.EndPointBehaviour"
          binding="webHttpBinding" bindingConfiguration="" name="VMS.Position.EndPoint"
          contract="VirtusMobileService.IContactPositionService" />
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="VMS.Position.EndPointBehaviour">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="VMS.ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior name="VMS.Position.ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

在Client Asp.net页面,我们调用服务添加Contact person对象,如下所示:

private void AddData()
        {
            string sURL = "http://localhost:51293/ContactPositionService.svc/AddContactPosition";       
            ContactPosition order = new ContactPosition
            {
                PositionCode="10550",
                PositionFinbaseId=11,
                PositionTitle="Manager"
            };

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ContactPosition));
            MemoryStream mem = new MemoryStream();
            ser.WriteObject(mem, order);
            string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
            WebClient webClient = new WebClient();
            webClient.Headers["Content-type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;
            webClient.UploadData(sURL, "PUT", mem.ToArray());         // Here it is showing Error
             Console.WriteLine("Order placed successfully...");  

}

虽然它涉及到,&#34; uploadData&#34;它显示错误,如&#34;  远程服务器返回错误:(404)Not Found。&#34;

If i am trying to Get the Data using the   "GetContactPositionList"

它正确地显示数据,但是当我尝试使用时  &#34; PUT&#34;它显示错误的方法。

我测试了Fiddler中的url,它在Response中显示相同的错误  标题&#34; HTTP / 1.1 405方法不允许&#34;

<div id="content">
      <p class="heading1">Service</p>
      <p xmlns="">Method not allowed. Please see the <a rel="help-page" href="http://localhost:51293/ContactPositionService.svc/help">service help page</a> for constructing valid requests to the service.</p>
    </div>

请建议答案。

感谢。

3 个答案:

答案 0 :(得分:0)

在提琴手中,您必须将application/json指定为Content Type,它才会点击服务Try this link

答案 1 :(得分:0)

代替“webClient.UploadData”,试试这个..    webClient.UploadString(sURL,“PUT”,data);

答案 2 :(得分:0)

我认为你可以使用System.ServiceModel.ChannelFactory让自己更轻松。它将大大简化您与服务的交互,因为您将拥有强类型变量,方法名称本身,而不必自己搞乱序列化。

您可以将AddData方法替换为:

private void AddData()
{
    // Create the service channel; 'factory' and/or 'svc' can be class members so we can re-use them.
    var factory = new ChannelFactory<IContactPositionService>(new WebHttpBinding(), new EndpointAddress("http://localhost:51293/ContactPositionService.svc"));
    factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
    var svc = factory.CreateChannel();

    ContactPosition order = new ContactPosition
    {
        PositionCode = "10550",
        PositionFinbaseId = 11,
        PositionTitle = "Manager"
    };

    try
    {
        var result = svc.AddContactPosition(order);
        Console.WriteLine("Order# " + result.ToString() + " placed successfully...");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

注意:这将要求您的调用项目具有对System.ServiceModel.dll和System.ServiceModel.Web.dll的引用。此外,调用项目需要了解IContactPositionServiceContactPosition。我的调用项目与您的WCF项目不同,并且尚未引用您的WCF项目,然后您可以将服务接口和对象移动到第三类库,然后您可以在WCF主机和任何使用者之间共享。