使用RestSharp调用Web API后请求模型为Null的问题排查
问题排查:RestSharp调用Web API时请求模型为Null的原因及解决方法
问题描述
使用RestSharp库调用Web API,调用Execute方法后,Web API端的请求模型(SapInvoiceRequestModel)始终为Null。以下是客户端与API端代码:
客户端代码
public BaseResponseDTO<InvoiceResponseDTO> GetInvoiceInfo(InvoiceRequestDTO model) { _client.BaseUrl = new System.Uri(_serviceUrl + "/Invoice/GetInvoiceInfo"); _request.Method = RestSharp.Method.POST; _request.AlwaysMultipartFormData = true; _request.UseDefaultCredentials = true; _request.AddParameter("SupplierCode", model.SupplierCode); _request.AddParameter("CompanyCode", model.CompanyCode); _request.AddParameter("Creator", model.Creator); _request.AddParameter("Type", model.Type); IRestResponse response = _client.Execute(_request); var result = JsonConvert.DeserializeObject<BaseResponseDTO<InvoiceResponseDTO>>(response.Content); return result; }
API端代码
[Route("GetInvoiceInfo")] [HttpPost] public GenericResponse Invoice([FromBody] SapInvoiceRequestModel model) { GenericResponse result = new GenericResponse(); try { ZMC_TD_BILLINFO billinfo = new ZMC_TD_BILLINFO(); var response = billinfo.CallZMC_TD_BILLINFO(new ZMC_TD_BILLINFO1 { GV_BUKRS = model.CompanyCode, GV_LIFNR= model.SupplierCode, GV_USNAM = model.Creator, GV_TYPE = model.Type, T_HEADER = new ZBILLHEADERINFO[0] }); result.Data = response; result.IsSuccess = true; result.Message = ""; } catch (Exception ex) { result.Message = ex.Message; result.IsSuccess = false; } return result; }
原因分析
- 客户端设置了
AlwaysMultipartFormData = true,并通过AddParameter逐个添加参数,此时请求内容以multipart/form-data格式发送。但API端使用[FromBody]特性接收模型,该特性期望请求体为JSON格式,两者格式不匹配,导致模型无法正确绑定,最终为Null。 AddParameter在multipart模式下仅会添加表单字段,而非JSON结构的属性,API无法将表单数据解析为指定的模型对象。
解决方法
方法一:发送JSON格式请求体(推荐)
修改客户端代码,移除AlwaysMultipartFormData设置,将请求模型序列化为JSON并作为请求体发送:
public BaseResponseDTO<InvoiceResponseDTO> GetInvoiceInfo(InvoiceRequestDTO model) { _client.BaseUrl = new System.Uri(_serviceUrl + "/Invoice/GetInvoiceInfo"); _request.Method = RestSharp.Method.POST; _request.UseDefaultCredentials = true; // 将模型序列化为JSON,添加到请求体 var jsonBody = JsonConvert.SerializeObject(model); _request.AddStringBody(jsonBody, ContentType.Json); IRestResponse response = _client.Execute(_request); var result = JsonConvert.DeserializeObject<BaseResponseDTO<InvoiceResponseDTO>>(response.Content); return result; }
方法二:API端改为接收表单数据(仅适用于特殊场景)
若必须使用表单格式发送数据,可修改API端代码,将[FromBody]替换为[FromForm]:
[Route("GetInvoiceInfo")] [HttpPost] public GenericResponse Invoice([FromForm] SapInvoiceRequestModel model) { // 原有业务逻辑代码不变 }
说明:推荐使用方法一,JSON格式是REST API的标准请求体格式,兼容性和规范性更好。
内容的提问来源于stack exchange,提问作者Emre Oztoprak
相关产品推荐
相关产品推荐

