难以在与服务相同的解决方案中调用测试项目中的localhost上运行的WCF POST服务

时间:2014-12-01 04:08:40

标签: c# wcf rest config

我在开发和测试接收并返回JSON的POST Web服务时遇到问题。 我正在测试它(或尝试/想要测试它),通过从同一个测试项目中的表单调用它 解决方案作为Web服务。然而似乎无论我做什么,我都会得到一个“错误请求”,或者 调用服务时出现“Not Found”错误。

网上有大量关于这些事情的帖子,以及一般的WCF,有例子等,但我 似乎无法解决问题而且令人沮丧: - ((。

我正在使用VS 2010(不要笑)赢得XP。但是我不明白为什么过时的操作系统应该重要。

单个方法的签名是

public Stream ReceiveCardStatusInfo(Stream request)

我已经通过svcutil生成了代理,但我没有使用它。我尝试过引用webservice项目 普通服务和服务引用(当前是服务引用)。项目的属性是 几乎是默认值,但在尝试解决问题时,WS项目的网页当前显示 选中“使用Visual Studio开发服务器”并选择“特定端口”,端口号为1318.(虚拟路径为 默认“/”)。

由于我不确定问题是什么,我提供了所有代码和配置文件; 表单的逻辑首先(用于调用服务)和该项目的app.config与服务 组件如下:

Form1中:

public Form1() {
  InitializeComponent();
}

public void button1_Click(object sender, EventArgs e) {
  var request = (HttpWebRequest)WebRequest.Create("http://localhost:1318/ReceiveData.svc/ReceiveCardStatusInfo"); // /ReceiveCardStatusInfo
  request.ContentType = "text/json";
  request.Method = "POST";

  string json = new JavaScriptSerializer().Serialize(new {
    AuthenticationToken = "...",
    Campus = "Te Awamutu",
    StudentID = "200122327",
    EnrolmentEndDate = "11/06/2015",
    CardStatus = "Suspended",
    SuspendedDate = "18/08/2014",
    OrderedDate = "20/09/2014",
    ReprintDate = "07/10/2014"
  });

  using (var sW = new StreamWriter(request.GetRequestStream())) {
    sW.Write(json);
    sW.Flush();
    sW.Close();
  }

  var response = (HttpWebResponse)request.GetResponse();
  string result;
  using (var streamReader = new StreamReader(response.GetResponseStream())) {
    result = streamReader.ReadToEnd();
  }

  MessageBox.Show(result);
}

app.config(我真的不明白这个文件中究竟需要什么,但我很难找到 明确答案,所以它包含它的作用):

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="StudentCardStatusData.ReceiveData" behaviorConfiguration="serviceBehaviour">
        <endpoint address="" binding="webHttpBinding" contract="StudentCardStatusData.IReceiveData" behaviorConfiguration="web"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBinding_IReceiveData" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        </binding>
      </webHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:1318/ReceiveData.svc" binding="webHttpBinding" bindingConfiguration="webHttpBinding_IReceiveData" contract="IReceiveData" name="webHttpBinding_IReceiveData"/>
      <!-- endpoint address="..." binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IReceiveData" contract="IReceiveData"
            name="BasicHttpBinding_IReceiveData" / -->
    </client>
  </system.serviceModel>
  <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
</configuration>

网络服务:

IReceiveData:

namespace StudentCardStatusData {
  [DataContract]
  public class StatusInfo {
    private string _Authent;
    private string _Campus;
    private string _StudentID;
    private string _EnrolmentEndDate;
    private string _CardStatus;
    private string _SuspendedDate;
    private string _OrderedDate;
    private string _ReprintDate;

    [DataMember(Name="AuthenticationToken")]
    public string AuthenticationToken {
      get { return _Authent; }
      set { _Authent = value; }
    }

    [DataMember(Name="Campus")]
    public String Campus {
      get { return _Campus; }
      set { _Campus = value; }
    }
    [DataMember(Name="StudentID")]
    public String StudentID {
      get { return _StudentID; }
      set { _StudentID = value; }
    }
    [DataMember(Name="EnrolmentEndDate")]
    public String EnrolmentEndDate {
      get { return _EnrolmentEndDate; }
      set { _EnrolmentEndDate = value; }
    }
    [DataMember(Name="CardStatus")]
    public String CardStatus {
      get { return _CardStatus; }
      set { _CardStatus = value; }
    }
    [DataMember(Name="SuspendedDate")]
    public String SuspendedDate {
      get { return _SuspendedDate; }
      set { _SuspendedDate = value; }
    }
    [DataMember(Name = "OrderedDate")]
    public String OrderedDate {
      get { return _OrderedDate; }
      set { _OrderedDate = value; }
    }
    [DataMember(Name = "ReprintDate")]
    public String ReprintDate {
      get { return _ReprintDate; }
      set { _ReprintDate = value; }
    }
  }

  [ServiceContract]
  public interface IReceiveData {
    [OperationContract]
    [WebInvoke(Method = "POST",
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json,
               BodyStyle = WebMessageBodyStyle.Bare,
               UriTemplate = "ReceiveCardStatusInfo")]
    Stream ReceiveCardStatusInfo(Stream request);
  }
}

ReceiveData.svc:

namespace StudentCardStatusData {

  public class ReceiveData : IReceiveData {

    public Stream ReceiveCardStatusInfo(Stream request) {
      Stream res = new MemoryStream();
      StreamWriter sw = new StreamWriter(res);
      try {
        ConnectionStringSettings _DefaultSetting = ConfigurationManager.ConnectionStrings["Take2"];
        SqlConnection cnn = new SqlConnection(_DefaultSetting.ConnectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cnn;
        //
        if (request != null) {
          StreamReader sr = new StreamReader(request);
          var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
          List<StatusInfo> allitems = serializer.Deserialize<List<StatusInfo>>(sr.ReadToEnd());
          bool isFirst = true;

          foreach (var item in allitems) {
            if (isFirst) {
              cmd.CommandType = System.Data.CommandType.Text;
              cmd.CommandText = "SELECT Cast(AuthenticationKey as varchar(50)) FROM IDCardAuthentication";
              cmd.Connection.Open();
              object o = cmd.ExecuteScalar();
              cmd.Connection.Close();
              if ((string)o != item.AuthenticationToken.ToUpper()) {
                sw.Write("[{\"Result\":\"Undefined Failure\"}]");
                return res;
              }
              isFirst = false;
            }
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = "dbo.spSaveStudentCardStatus";
            cmd.Parameters.Add(new SqlParameter("@Campus", item.Campus));
            cmd.Parameters.Add(new SqlParameter("@PerID", item.StudentID));
            cmd.Parameters.Add(new SqlParameter("@EndDate", item.EnrolmentEndDate));
            cmd.Parameters.Add(new SqlParameter("@Status", item.CardStatus));
            cmd.Parameters.Add(new SqlParameter("@Upload", item.SuspendedDate));
            cmd.Parameters.Add(new SqlParameter("@Ordered", item.OrderedDate));
            cmd.Parameters.Add(new SqlParameter("@Reprint", item.ReprintDate));
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
          }
        }
        sw.Write("[{\"Result\":\"Success\"}]");
        return res;
      }
      catch (Exception ex) {
        sw.Write("[{\"Result\":\"" + ex.Message + "\"}]");
        return res;
     }
    }
  }
}

Web.Config中:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="Take2"
      connectionString="..."
      providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>


  <system.serviceModel>
    <services>
      <service name="StudentCardStatusData.ReceiveData" behaviorConfiguration="StudentCardStatusData.ReceiveDataBehavior"> 
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="StudentCardStatusData.IReceiveData" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="https://localhost:1318/ReceiveData.svc" />
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="StudentCardStatusData.ReceiveDataBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <bindings>
      <webHttpBinding>
        <binding maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        </binding>
      </webHttpBinding>
    </bindings>

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


  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

1 个答案:

答案 0 :(得分:2)

在您的情况下,首先要求使用任何服务是“本地ISS中的”服务已启动且正在运行“。

调用服务时出现“错误请求”或“未找到”错误的原因可能是它未在服务器(localhost)上运行。

您是否可以通过端点上的“ReceiveData.svc”页面的HTTP请求从浏览器查看服务页面。

如果没有,那么在开始使用之前,您必须确保您的服务已准备好运行。

正如您所说,您是从相同的解决方案运行它,我相信您同时说明了多个应用程序。我的意思是服务申请和消费申请。

如果没有,您可以通过

中的设置从同一解决方案运行多个启动应用程序

转到解决方案属性 - &gt;共同属性 - &gt;启动项目并选择多个启动项目。

现在,当您运行解决方案时,您的两个应用程序都将启动,您应该可以使用服务。

修改

我使用您提供的所有代码创建了测试应用程序.. !!

它给了我同样的错误.. !!!! 所以我改变了;

  request.ContentType = "'text/json; charset=utf-8'";

它工作.. !!! ;)

所以请试试。 希望它有所帮助.. !!