C# Web服务WebInvoke手动反序列化请求体失败求助
解决C# Web服务手动读取请求体并反序列化的问题
核心思路
默认参数绑定机制不会把整个请求体映射到string参数,要实现手动反序列化,需直接从请求流中读取原始内容,再自行完成序列化转换。
ASMX Web服务实现示例
1. 修改Web服务方法
移除原string参数,在方法内部读取请求体:
using System.IO; using System.Web; using System.Web.Services; using System.Xml.Serialization; [WebService(Namespace = "http://your-custom-namespace.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class CustomWebService : WebService { [WebMethod] public string HandleRequest() { // 读取原始请求体内容 string rawRequestBody; using (StreamReader reader = new StreamReader(Context.Request.InputStream)) { // 重置流位置,避免因前置操作导致读取为空 Context.Request.InputStream.Position = 0; rawRequestBody = reader.ReadToEnd(); } // 手动反序列化到自定义Action结构体 XmlSerializer serializer = new XmlSerializer(typeof(Action)); using (StringReader stringReader = new StringReader(rawRequestBody)) { Action actionData = (Action)serializer.Deserialize(stringReader); // 执行业务逻辑 return $"处理完成:{actionData.ActionName} | 参数:{actionData.Parameter}"; } } }
2. 自定义Action结构体示例
[Serializable] public struct Action { public string ActionName { get; set; } public string Parameter { get; set; } }
3. Web.config基础配置
保持默认请求协议配置即可,无需额外修改:
<system.web> <webServices> <protocols> <add name="HttpPost"/> <add name="HttpGet"/> </protocols> </webServices> </system.web>
WCF Web服务实现方式
如果是WCF服务,通过OperationContext获取请求流:
using System.IO; using System.ServiceModel; using System.ServiceModel.Web; using Newtonsoft.Json; [ServiceContract] public interface ICustomService { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/HandleRequest")] string HandleRequest(); } public class CustomService : ICustomService { public string HandleRequest() { // 获取请求流 Stream requestStream = WebOperationContext.Current.IncomingRequest.ContentStream; string rawRequestBody; using (StreamReader reader = new StreamReader(requestStream)) { rawRequestBody = reader.ReadToEnd(); } // JSON格式反序列化示例(若请求为JSON) Action actionData = JsonConvert.DeserializeObject<Action>(rawRequestBody); return $"处理完成:{actionData.ActionName}"; } }
关键注意事项
- 读取请求流前必须重置
Position为0,否则可能因框架前置读取操作导致内容为空 - 根据实际请求格式选择序列化器:XML用
XmlSerializer,JSON用Newtonsoft.Json或System.Text.Json - 无需依赖参数绑定传递请求体,直接读取原始流是最稳定的实现方式
内容的提问来源于stack exchange,提问作者CPipe
相关产品推荐
相关产品推荐

