【发布时间】:2012-02-05 12:55:18
【问题描述】:
我创建了一个简单的 RESTful WCF 服务,它具有一个用于接收文件的单一方法和一个用于上传文件的简单客户端。这些文件是简单的文本文件(当然我想稍后上传二进制文件)。
该服务将为多种类型的客户端发布,因此我想使用不添加服务引用的实现。
我这样做对吗?
当我尝试上传简单的 1Mb 文本文件时,为什么会收到 远程服务器返回意外响应:(400) Bad Request 错误?
编辑: 如果我的文件只有 3.7kb 大小,则系统可以正常工作。这意味着我只需将服务配置为接受更大的数据包。我该怎么做?
服务:
/// <summary>
/// Data Service REST service that handles data upload.
/// </summary>
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DataService : Common.Contracts.IDataService
{
/// <summary>
/// Uploads a data file to the server.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="fileContent">Content of the file.</param>
public string UploadFile(string filename, Stream fileContent)
{
return filename;
}
}
服务配置
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address
via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
合同:
/// <summary>
/// Data Service service contract interface.
/// </summary>
[ServiceContract]
public interface IDataService
{
/// <summary>
/// Uploads a data file to the server.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="fileContent">Content of the file.</param>
[WebInvoke(UriTemplate = "/upload?filename={filename}",
Method = "POST", ResponseFormat = WebMessageFormat.Xml)]
string UploadFile(string filename, System.IO.Stream fileContent);
}
客户
WebChannelFactory<IDataService> cf =
new WebChannelFactory<IDataService>(
new Uri(Settings.Default.UrlService));
IDataService channel = cf.CreateChannel();
StreamReader fileContent = new StreamReader(path, false);
string response = channel.UploadFile(path, fileContent.BaseStream);
【问题讨论】:
-
你能在你的配置文件中发布服务器和客户端配置吗?
-
这就是我所拥有的。 web.config 文件是默认生成的。因为我的客户不应该强烈依赖 Web 服务,所以我没有添加服务引用。你觉得我应该有吗?
-
你在哪里定义了你的端点?
-
我添加了我的服务的
部分。它从未被触及,这就是它的生成方式。我希望这是你提到的问题。我真的是个菜鸟。
标签: c# wcf web-services rest web