gpt4 book ai didi

c# - 在与服务相同的解决方案中,难以在测试项目中调用在本地主机上运行的 WCF POST 服务

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:14 25 4
gpt4 key购买 nike

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

网上有很多关于这些事情的帖子,一般来说是 WCF,还有例子等等,但我似乎无法解决问题,这令人非常沮丧:-((。

我在(别笑)Win XP 上使用 VS 2010。但是,我不明白为什么过时的操作系统应该很重要。

单一方法的签名是

public Stream ReceiveCardStatusInfo(Stream request)

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

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

表格 1:

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

接收数据.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;
}
}
}
}

网络配置:

<?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>

最佳答案

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

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

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

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

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

如果没有,您可以通过中的设置从同一解决方案运行多个启动应用程序

转到解决方案属性 -> 通用属性 -> 启动项目并选择多个启动项目。

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

编辑

我用你所有给定的代码创建了测试应用程序..!!

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

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

它奏效了..!!! ;)

所以请尝试一下。希望对您有所帮助..!!

关于c# - 在与服务相同的解决方案中,难以在测试项目中调用在本地主机上运行的 WCF POST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27221574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com