gpt4 book ai didi

c# - Web API 返回 UTF-16

转载 作者:太空宇宙 更新时间:2023-11-03 14:52:21 25 4
gpt4 key购买 nike

我有一个简单的测试接口(interface)

[Route("api/[controller]")]
[Produces("application/json")]
[ApiController]
public class ValuesController : ControllerBase
{

[HttpPost]
public IActionResult Post([FromBody] FulfillmentRequst data)
{
var obj = new DummyObject();
Ok(obj)
}
}

问题可以在日志中看到,post 请求以 UTF-8 格式传入,但响应以 UTF-16 格式发出。

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/1.1 POST http://371395ef.ngrok.io/api/values application/json; charset=UTF-8 3401

info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Route matched with {action = "Post", controller = "Values"}. Executing action WebApplicationAPI.Controllers.ValuesController.Post (WebApplicationAPI)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Executing action method
WebApplicationAPI.Controllers.ValuesController.Post (WebApplicationAPI) with arguments (ActionsOnGoogle.Core.v2.Request.FulfillmentRequst) - Validation state: Valid
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] Executed action method WebApplicationAPI.Controllers.ValuesController.Post (WebApplicationAPI), returned result Microsoft.AspNetCore.Mvc.OkObjectResult in 8.796ms.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1] Executing ObjectResult, writing value of type 'ActionsOnGoogle.Core.v2.Response.SimpleResponseResponse'.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] Executed action WebApplicationAPI.Controllers.ValuesController.Post (WebApplicationAPI) in 267.2988ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] Request finished in 508.7373ms 200 application/json; charset=utf-16

这是一个全新的 .net 核心 web api。我没有在设置中更改任何内容。当从 API 返回 json 响应时,如何强制它返回 utf-8。

主要问题是另一个从 Web Hook 读取的服务器显然无法处理 utf-16 并将其解析为垃圾。

Expect message object but got: \"笀∀瀀愀礀氀漀愀搀∀㨀笀∀最漀漀最氀攀∀㨀笀∀攀砀瀀攀挀琀唀猀攀爀刀攀猀瀀漀渀猀攀∀㨀琀爀甀攀Ⰰ∀爀椀挀栀刀攀猀瀀漀渀猀攀∀㨀笀∀椀琀攀洀猀∀㨀嬀笀∀猀椀洀瀀氀攀刀攀猀瀀漀渀猀攀∀㨀笀∀琀攀砀琀吀漀匀瀀攀攀挀栀∀㨀∀圀伀刀䬀 䐀䄀䴀䤀吀∀紀紀崀紀紀紀紀\"."

最佳答案

基本上,您可以使用 Charset 属性强制响应。类似的东西:

public class CharsetAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.Headers["Content-Type"] += ";charset=utf-8";
}
}

关于c# - Web API 返回 UTF-16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com