正在将文本文件上载到WCF RESTful服务
本文关键字:WCF RESTful 服务 上载 文件 文本 | 更新日期: 2023-09-27 18:19:55
我创建了一个简单的RESTful WCF服务,它有一个接收文件的方法和一个上传文件的简单客户端。这些文件都是简单的文本文件(当然我稍后会上传二进制文件)。
该服务将为许多类型的客户端发布,因此我希望使用不添加服务引用的实现。
我这样做对吗?
为什么我会收到远程服务器在我尝试上传一个简单的1Mb文本文件时返回了一个意外的响应:(400)错误请求错误?
编辑: 如果我的文件只有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);
您可以用以下元素替换您的standardEndpoint元素吗:
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxBufferSize="500000" maxReceivedMessageSize="500000" >
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</standardEndpoint>
希望能有所帮助。
也许这与您在配置绑定中设置的maxReceivedMessageSize有关。
当你上传一些非常小的东西时,你会得到400吗?