难以在与服务相同的解决方案中调用在本地主机上运行的 WCF POST 服务
本文关键字:服务 主机 POST 运行 WCF 解决方案 调用 | 更新日期: 2023-09-27 18:32:30
我在开发和测试接收和返回 JSON 的 POST Web 服务时遇到问题。我正在通过从同一测试项目中的表单调用它来测试它(或尝试/想要测试它(解决方案即 Web 服务。但是,似乎无论我做什么,我都会收到"错误请求",或者调用服务时出现"未找到"错误。
网络上有很多关于这些事情的帖子,一般是WCF,有例子等,但我似乎无法解决问题,这非常令人沮丧:-((。
我正在使用VS 2010(不要笑(赢得XP。但是我不明白为什么过时的操作系统应该很重要。
单个方法的签名是
public Stream ReceiveCardStatusInfo(Stream request)
我已经通过 svcutil 生成了一个代理,但我没有使用它。我尝试将网络服务项目引用为普通引用和服务引用(当前为服务引用(。项目的属性是几乎是默认值,但在尝试解决问题时,WS 项目的网页当前显示"使用 Visual Studio 开发服务器",选择"特定端口",端口号 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);
}
}
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;
}
}
}
}
网络配置:
<?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'";
它奏效了..!! ;)
所以请尝试一下。希望对您有所帮助..!!