PHP POST接收代码转C# .NET Core,解决x-www-form-urlencoded请求415错误
解决方案
415 Unsupported Media Type报错的根因是ASP.NET Core默认POST接口未显式指定表单绑定时,会默认期望JSON格式请求体,无法匹配第三方发送的application/x-www-form-urlencoded格式请求,可按以下步骤修改:
修改步骤
- 接口方法上添加
[Consumes("application/x-www-form-urlencoded")]特性,显式声明接口支持的请求媒体类型 - 所有接收的表单参数前添加
[FromForm]特性,指定参数从表单字段中绑定 - 补全第三方提交的
oo_id参数,避免字段遗漏
修改后的完整代码
[HttpPost("b_notice")] [Consumes("application/x-www-form-urlencoded")] [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)] public async Task<ActionResult> APIUrl([FromForm] string mm_id, [FromForm] string oo_id) { try { // 此处添加业务逻辑 return Ok(mm_id); } catch (Exception ex) { return BadRequest(ex.Message); } }
拓展说明(参数较多时推荐)
如果后续需要接收的表单字段较多,可封装为专用接收模型,代码可维护性更高:
- 定义接收模型类
public class ThirdPartyNoticeDto { public string mm_id { get; set; } public string oo_id { get; set; } // 可按需扩展其他接收字段 }
- 调整接口参数
[HttpPost("b_notice")] [Consumes("application/x-www-form-urlencoded")] [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)] public async Task<ActionResult> APIUrl([FromForm] ThirdPartyNoticeDto notice) { try { // 可通过notice.mm_id、notice.oo_id直接访问参数 return Ok(notice.mm_id); } catch (Exception ex) { return BadRequest(ex.Message); } }
内容的提问来源于stack exchange,提问作者Illep
相关产品推荐
相关产品推荐

