.NET API POST端点无法被控制台应用调用问题求助
问题描述
我有一个.NET API,想用控制台应用测试其中的POST方法。把控制台里的数据序列化成JSON字符串后发送到API,但POST端点始终无法被命中,控制台也没有任何错误提示。不过GET请求正常,只有POST有问题。
API控制器代码
using _ErrorLogger.Shared; using _ErrorLogger.Server.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Runtime.CompilerServices; namespace _ErrorLogger.Server.Controllers { [Route("api/[controller]")] [ApiController] public class ExceptionDetailsController : ControllerBase { private readonly IExceptionDetailsService _exceptionDetailsService; public ExceptionDetailsController(IExceptionDetailsService exceptionDetailsService) { _exceptionDetailsService = exceptionDetailsService; } [HttpGet] [Route("GetExceptions")] public async Task<List<ExceptionDetails>> GetAll() { return await _exceptionDetailsService.GetAllExceptionDetails(); } [HttpGet] [Route("GetExceptionByID/{id}")] public async Task<ExceptionDetails> GetByID(int id) { return await _exceptionDetailsService.GetExceptionDetails(id); } [HttpPost] [Route("CreateException")] public async Task<IActionResult> CreateException([FromBody]string obj) { //await _exceptionDetailsService.AddExceptionDetails(exceptionDetails); return Ok(); } [HttpPost] [Route("Test")] public async Task<IActionResult> Test([FromBody] string obj) { return Ok(); } } }
控制台应用调用代码
public async void ExceptionsAnalyzer(Exception exception) { HttpClient _httpClient = new HttpClient(); StackTrace stack = new StackTrace(exception, true); StackFrame frame = stack.GetFrame(stack.FrameCount - 1); ExceptionDetails exceptionDetails = new ExceptionDetails { ExceptionMessage = exception.Message, InnerException = exception.InnerException?.ToString(), ExceptionType = exception.GetType().ToString(), ExceptionSourceFile = frame.GetFileName(), ExceptionSourceLine = frame.GetFileLineNumber().ToString(), ExceptionCaller = frame.GetMethod().ToString(), ExceptionStackTrace = exception.StackTrace, DateLogged = DateTime.Now }; string json = JsonSerializer.Serialize(exceptionDetails); //var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await _httpClient.PostAsJsonAsync("http://localhost:5296/api/ExceptionDetails/CreateException", json); if (response.IsSuccessStatusCode) { } }
解决方案
核心问题是请求数据格式与API接收参数不匹配,外加异步代码的潜在问题,具体修复如下:
1. 修正数据格式不匹配问题
你的API端点CreateException接收的是[FromBody]string obj,但使用PostAsJsonAsync发送序列化后的exceptionDetails时,会把JSON字符串再次包装成JSON格式(相当于发送了带嵌套引号的字符串,比如"{...}"),导致API无法解析,返回400错误,但你未处理非成功响应所以看不到提示。
有两种修复方案:
方案一(推荐,符合REST规范):修改API接收对象
直接让API接收ExceptionDetails类型,无需手动处理字符串序列化:
[HttpPost] [Route("CreateException")] public async Task<IActionResult> CreateException([FromBody] ExceptionDetails exceptionDetails) { await _exceptionDetailsService.AddExceptionDetails(exceptionDetails); return Ok(); }
控制台代码无需修改,PostAsJsonAsync会自动正确序列化exceptionDetails对象。
方案二:保持API接收字符串,修正控制台请求方式
如果必须保持API接收字符串,改用StringContent发送原始JSON字符串,避免二次序列化:
var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await _httpClient.PostAsync("http://localhost:5296/api/ExceptionDetails/CreateException", stringContent);
2. 修复异步代码隐患
- 避免使用
async void,改用async Task,否则无法捕获异步操作中的异常:public async Task ExceptionsAnalyzer(Exception exception) { // 原有代码逻辑 } - 增加错误响应处理,方便排查问题:
if (!response.IsSuccessStatusCode) { string errorMsg = await response.Content.ReadAsStringAsync(); Console.WriteLine($"请求失败:{response.StatusCode},详情:{errorMsg}"); }
内容的提问来源于stack exchange,提问作者MarkBerry
相关产品推荐
相关产品推荐

