HTML+MVC WCF服务报413请求实体过大错误求助
解决413 Request Entity Too Large错误
大文件传输时出现413错误,本质是WCF和ASP.NET的请求大小限制导致的,需从两方面调整配置:
1. WCF绑定配置调整
在项目web.config中找到WCF绑定节点(如basicHttpBinding或webHttpBinding),修改参数以支持大请求:
<system.serviceModel> <bindings> <!-- SOAP服务用basicHttpBinding --> <basicHttpBinding> <binding name="LargeFileBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647"> <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </binding> </basicHttpBinding> <!-- REST服务用webHttpBinding --> <webHttpBinding> <binding name="RestLargeFileBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647"> <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </binding> </webHttpBinding> </bindings> <!-- 确保端点使用上述绑定配置 --> <services> <service name="你的命名空间.你的服务类"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="LargeFileBinding" contract="你的命名空间.你的服务契约" /> <!-- REST服务替换为: <endpoint address="" binding="webHttpBinding" bindingConfiguration="RestLargeFileBinding" contract="你的命名空间.你的服务契约" behaviorConfiguration="WebBehavior" /> --> </service> </services> </system.serviceModel>
替换配置中的命名空间、服务类和契约接口为实际名称。
2. ASP.NET请求大小限制调整
MVC项目中,ASP.NET本身也有请求大小限制,在web.config的system.web节点下添加:
<system.web> <httpRuntime targetFramework="你的.NET版本" maxRequestLength="2097151" executionTimeout="3600" /> </system.web>
maxRequestLength单位为KB,2097151对应2GB;executionTimeout设置超时时间,避免大文件传输超时。
若为.NET 4.5+项目,还需在system.webServer节点补充:
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer>
maxAllowedContentLength单位为字节,2147483647对应2GB。
JavaScript字符串转Stream方法
以下两种方法可将字符串转为浏览器支持的Stream,适配WCF的Stream类型参数:
方法1:利用Blob原生转Stream
这是最简洁的实现,根据文件类型指定MIME:
function stringToStream(str, mimeType) { const blob = new Blob([str], { type: mimeType }); return blob.stream(); } // 使用示例:XML文件传"application/xml",SVG传"image/svg+xml" const xmlStream = stringToStream('<root>...</root>', 'application/xml');
方法2:手动编码生成ReadableStream
若需要更底层控制,可通过TextEncoder将字符串转为UTF-8字节数组再包装成Stream:
function stringToReadableStream(str) { const encoder = new TextEncoder(); const encodedBytes = encoder.encode(str); return new ReadableStream({ start(controller) { controller.enqueue(encodedBytes); controller.close(); } }); }
发送Stream到WCF服务
用fetch发送请求时,直接将Stream作为请求体传入:
const svgStr = '<svg>...</svg>'; const stream = stringToStream(svgStr, 'image/svg+xml'); fetch('http://你的服务地址/UploadStream', { method: 'POST', body: stream, headers: { 'Content-Type': 'image/svg+xml' } }) .then(res => res.json()) .catch(err => console.error('传输失败:', err));
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

