.NET Core迁移后IActionResult无法返回预期字符串响应
问题:.NET Core Web API迁移后无法返回纯字符串响应
原ASP.NET Web API可正常返回纯字符串结果:
[HttpPost] public string ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber) { return _ewpDataAccess.ValidateEwpInspectionNumber(ewpNumber, inspectionNumber); }
该API在开发者工具中响应符合预期,直接返回字符串。
迁移至.NET Core后,改用IActionResult作为返回类型的API无法按原方式返回字符串,Angular将响应识别为对象而非字符串:
[HttpPost(nameof(ValidateEwpInspectionNumber))] [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] public async Task<IActionResult> ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber) { var response = await _ewpBusinessService.ValidateEwpInspectionNumberAsync(ewpNumber, inspectionNumber); return Ok(response); }
尝试过返回Content(response)、Content(response, 'text/plain'),以及替换为ActionResult<string>均未解决问题。
更新:发现Ok()默认返回JSON格式,若手动设置Content(response, 'application/json')会触发JSON解析错误:
can't parse JSON. Raw result:
NOTEXISTS
需要让.NET Core API像原API那样直接返回纯字符串。
解决方案
1. 明确返回纯文本格式的ContentResult
在API方法中,使用ContentResult明确指定内容类型为text/plain,确保响应不被JSON序列化:
[HttpPost(nameof(ValidateEwpInspectionNumber))] [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] public async Task<IActionResult> ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber) { var response = await _ewpBusinessService.ValidateEwpInspectionNumberAsync(ewpNumber, inspectionNumber); return new ContentResult { Content = response, ContentType = "text/plain", StatusCode = StatusCodes.Status200OK }; }
或者简化写法:
return Content(response, "text/plain", Encoding.UTF8);
2. 调整Angular端的响应解析方式
如果API已正确返回纯文本,但Angular仍解析为对象,需在HttpClient调用时指定responseType: 'text',避免默认的JSON解析:
this.http.post('/api/ValidateEwpInspectionNumber', { ewpNumber, inspectionNumber }, { responseType: 'text' }) .subscribe(result => { // result 会是纯字符串类型 });
3. 全局配置字符串返回格式(可选)
若多个API都需要返回纯字符串,可在Program.cs中配置输出格式化器,默认将字符串作为纯文本返回:
builder.Services.AddControllers(options => { options.OutputFormatters.RemoveType<StringOutputFormatter>(); options.OutputFormatters.Add(new StringOutputFormatter()); });
配置后,直接返回Ok(response)或使用ActionResult<string>返回字符串时,会自动以纯文本格式输出。
内容的提问来源于stack exchange,提问作者Pawan Nogariya
相关产品推荐
相关产品推荐

