我是 WCF 的新手,所以我认为这是非常基本的。我有一个简单的方法,它返回一个“订单”对象。使用默认 XML 时它工作得很好,但是,当我应用
ResponseFormat = WebMessageFormat.Json
属性,返回失败JSON
。代码成功执行并点击返回行,但随后立即再次调用该方法,最后在浏览器返回错误之前第三次调用,说明与 localhost 的连接已中断。
当我删除 时ResponseFormat = WebMessageFormat.Json
,调用该方法并返回 XML 就好了。不确定我是否缺少 JSON。
IProductSales.cs
namespace ProductsSalesService
{
[ServiceContract(Name = "ProductsSales")]
public interface IProductsSales
{
[OperationContract]
[WebGet(UriTemplate = "Orders/{orderID}", ResponseFormat = WebMessageFormat.Json)]
[Description("Returns the details of an order")]
SalesOrderHeader GetOrder(string orderID);
}
}
产品销售
public SalesOrderHeader GetOrder(string orderID)
{
SalesOrderHeader header = null;
try
{
int id = Convert.ToInt32(orderID);
AdventureWorksEntities database = new AdventureWorksEntities();
header = (from order in database.SalesOrderHeaders
where order.SalesOrderID == id
select order).FirstOrDefault();
}
catch
{
throw new WebFaultException(HttpStatusCode.BadRequest);
}
return header;
}
我正在研究 WCF 书中的一个示例,所以他们让我构建了一个小型控制台应用程序作为主机,所以这是我为主机客户端提供的 app.config 文件。
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="AdventureWorksEntities" connectionString="metadata=res://*/ProductsSalesModel.csdl|res://*/ProductsSalesModel.ssdl|res://*/ProductsSalesModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=BINGBONG;Initial Catalog=AdventureWorks;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup><system.serviceModel>
<services>
<service name="ProductsSalesService.ProductsSales">
<endpoint address="http://localhost:8000/Sales" binding="webHttpBinding"
bindingConfiguration="" name="ProductsSalesService.ProductsSales"
contract="ProductsSalesService.IProductsSales" />
</service>
</services>
</system.serviceModel>
</configuration>
最后,这只是主机客户端代码。
public class Program
{
static void Main(string[] args)
{
WebServiceHost host = new WebServiceHost(typeof(ProductsSalesService.ProductsSales));
host.Open();
Console.WriteLine("Service running");
Console.WriteLine("Press ENTER to stop the service");
Console.ReadLine();
host.Close();
}
}
因此,当我去http://localhost:8000/Sales/Orders/43659
拉起我的订单时,它点击了三次,并且页面在 Chrome 中取消,并出现以下错误:
此网页不可用 与 localhost 的连接已中断。以下是一些建议: 稍后重新加载此网页。检查您的互联网连接。重新启动您可能正在使用的任何路由器、调制解调器或其他网络设备。在防火墙或防病毒软件的设置中将 Google Chrome 添加为允许的程序。如果它已经是允许的程序,请尝试将其从允许的程序列表中删除并重新添加。如果您使用代理服务器,请检查您的代理设置或联系您的网络管理员以确保代理服务器正常工作。如果您认为您不应该使用代理服务器,请调整您的代理设置:转到扳手菜单 > 设置 > 显示高级设置... > 更改代理设置...
LAN 设置并取消选中“为 LAN 使用代理服务器”复选框。错误 101 (net::ERR_CONNECTION_RESET):连接已重置。
如果我删除WebMessageFormat.Json
一切正常!
感谢您的帮助!