开发Slack应用时命令响应无法被反序列化如何解决
问题根因
Slack 斜杠命令的响应要求JSON字段为小驼峰命名(比如response_type、text),但你当前返回的JSON是大驼峰命名(ResponseType、Text),和Slack要求的字段名不匹配,所以Slack无法识别结构,直接把完整JSON当作纯文本返回。
解决方案
方案1:配置JSON序列化规则输出小驼峰
如果是ASP.NET Core环境,修改JsonResult的序列化配置,强制将属性名转为小驼峰格式:
public JsonResult GetInfo() { var slackResponse = new Slack.Webhooks.SlackMessage() { ResponseType = "in_channel", Text = "Here is a response!" }; return new JsonResult(slackResponse, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 可选配置:忽略null值字段,减少返回体积 DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }) { ContentType = "application/json" }; }
如果是.NET Framework环境,使用Newtonsoft.Json的配置方式如下:
public JsonResult GetInfo() { var slackResponse = new Slack.Webhooks.SlackMessage() { ResponseType = "in_channel", Text = "Here is a response!" }; return new JsonResult() { ContentType = "application/json", Data = slackResponse, JsonRequestBehavior = JsonRequestBehavior.AllowGet, SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore } }; }
方案2:直接构造符合要求的匿名类返回
不想调整序列化规则的话,可以直接构造字段名符合Slack要求的匿名对象返回,更轻量:
public JsonResult GetInfo() { return new JsonResult(new { response_type = "in_channel", text = "Here is a response!" }) { ContentType = "application/json" }; }
额外校验项
- 确认接口返回的HTTP状态码为200 OK,Slack不会处理非200状态的响应
- 确认
response_type设置为in_channel,默认值ephemeral仅触发命令的用户可见
内容的提问来源于stack exchange,提问作者The Aurochs
相关产品推荐
相关产品推荐

