我创建了一个简单的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);
答案 0 :(得分:1)
您可以使用以下内容替换standardEndpoint元素:
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxBufferSize="500000" maxReceivedMessageSize="500000" >
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</standardEndpoint>
希望有所帮助。
答案 1 :(得分:0)
也许它与您在配置绑定中设置的maxReceivedMessageSize有关。
当你上传一些非常小的东西时,你会得到400吗?