WCF Rest服务GET长请求返回Error 400故障排查求助
问题根因
该问题由两个核心配置错误导致:
- 代码注册端点未加载自定义绑定配置:你在Main方法中直接
new WebHttpBinding()创建绑定,没有读取App.config中定义的webHttp绑定配置,你修改的maxReceivedMessageSize等参数完全未生效。 - Http.Sys路径段长度限制:Windows HTTP服务栈(Http.Sys)默认单段URL路径的最大长度为260字符,你将长JSON直接放在URL路径段中,超过阈值后会被Http.Sys直接拦截返回400,请求根本不会到达WCF层,因此WCF日志无记录、业务断点不命中。
修复步骤
步骤1:修复绑定配置不生效问题
二选一即可:
方案A:代码直接设置绑定参数(优先,避免配置冲突)
修改Main方法代码:
static void Main(string[] args) { WebServiceHost hostWeb = new WebServiceHost(typeof(ConsoleApp1.Service)); // 手动创建绑定并配置所有参数 WebHttpBinding binding = new WebHttpBinding() { OpenTimeout = TimeSpan.FromMinutes(10), CloseTimeout = TimeSpan.FromMinutes(10), SendTimeout = TimeSpan.FromMinutes(10), ReceiveTimeout = TimeSpan.FromHours(1), MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue, ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxStringContentLength = int.MaxValue }, Security = new WebHttpSecurity() { Mode = WebHttpSecurityMode.None } }; ServiceEndpoint ep = hostWeb.AddServiceEndpoint(typeof(ConsoleApp1.IService), binding, ""); // 添加WebHttp行为 ep.EndpointBehaviors.Add(new WebHttpBehavior()); ServiceDebugBehavior stp = hostWeb.Description.Behaviors.Find<ServiceDebugBehavior>(); stp.HttpHelpPageEnabled = false; stp.IncludeExceptionDetailInFaults = true; hostWeb.Open(); Console.WriteLine("Service Host started @ " + DateTime.Now.ToString()); Console.Read(); }
方案B:沿用App.config配置
删除Main方法中手动AddServiceEndpoint的代码,让WebServiceHost自动加载配置文件中的服务、绑定、行为配置即可。
步骤2:规避URL路径段长度限制
二选一即可:
方案A:参数移到查询字符串(小幅度改造成本)
修改接口的UriTemplate配置:
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "POINTINFO/{database}?pointlist={pointlist}")]
请求URL调整为http://IP:PORT/POINTINFO/DBNAME?pointlist=URL编码后的JSON字符串,注意JSON需要先做URL编码,避免特殊字符导致解析失败。
方案B:改成POST请求传Body(推荐,无长度限制)
如果后续参数还会变长,直接调整为POST请求,彻底规避URL长度限制:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "POINTINFO/{database}")] [return: MessageParameter(Name = "Data")] List<PointData> GetPointList(string database, PointQueryParams pointlist); // 新增参数映射类 public class PointQueryParams { public string User { get; set; } public string Pc { get; set; } public List<string> Data { get; set; } }
调用时将JSON放在POST请求Body中传递即可。
(不推荐)强制修改Http.Sys路径长度限制
如果必须保留原URL路径传参的逻辑,可修改注册表放开限制:
- 打开注册表编辑器,定位到
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters - 新建两个DWORD值:
UrlSegmentMaxLength:值设为0(无限制)或你需要的最大长度(单位为字符)MaxUrlLength:值设为你需要的最大URL总长度
- 管理员执行
net stop http && net start http重启HTTP服务,再重启WCF服务即可。
内容的提问来源于stack exchange,提问作者KardasR
相关产品推荐
相关产品推荐

