栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ASP.NET Core API POST参数始终为null

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ASP.NET Core API POST参数始终为null

问题是is

Content-Type
application/json
,而请求有效载荷实际上是
text/plain
。这将导致415不支持的媒体类型HTTP错误。

您至少有两个选项可以使

Content-Type
内容与实际内容对齐。

使用application / json

保留

Content-Type
as
application/json
并确保请求有效负载是有效的JSON。例如,使您的请求有效负载为:

{    "cookie": "=sec_session_id=[redacted]; _ga=[redacted]; AWSELB=[redacted]"}

然后,动作签名需要接受与JSON对象具有相同形状的对象。

public class cookieWrapper{    public string cookie { get; set; }}

代替

cookieWrapper
类,或者您可以接受动态或a
Dictionary<string,string>
并像
cookie["cookie"]
在端点中那样对其进行访问

public IActionResult GetRankings([FromBody] cookieWrapper cookie)public IActionResult GetRankings([FromBody] dynamic cookie)public IActionResult GetRankings([FromBody] Dictionary<string, string> cookie)

使用文字/纯文字

另一种选择是将项目更改

Content-Type
text/plain
,并向项目中添加纯文本输入格式器。为此,请创建以下类。

public class TextPlainInputFormatter : TextInputFormatter{    public TextPlainInputFormatter()    {        SupportedMediaTypes.Add("text/plain");        SupportedEncodings.Add(UTF8EncodingWithoutBOM);        SupportedEncodings.Add(UTF16EncodingLittleEndian);    }    protected override bool CanReadType(Type type)    {        return type == typeof(string);    }    public override async Task<InputFormatterResult> ReadRequestBodyAsync(        InputFormatterContext context,         Encoding encoding)    {        string data = null;        using (var streamReader = context.ReaderFactory( context.HttpContext.Request.Body,  encoding))        { data = await streamReader.ReadToEndAsync();        }        return InputFormatterResult.Success(data);    }}

并配置Mvc以使用它。

services.AddMvc(options =>{    options.InputFormatters.Add(new TextPlainInputFormatter());});

也可以看看

https://github.com/aspnet/Mvc/issues/5137



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449068.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号