You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core JWT Web API出现415不支持的媒体类型错误

解决.NET Core JWT API表单提交415 Unsupported Media Type错误

错误原因

你遇到的415错误核心问题:

  • 表单默认提交的是application/x-www-form-urlencoded格式数据,但API接口用[FromBody]要求接收application/json格式的请求体,服务器无法识别请求格式,返回不支持的媒体类型错误。
  • 你的Razor页面OnPost方法写法完全错误:既用[FromBody]又读取Request.Form,且修改Request.ContentType无法改变已发送请求的内容类型,这个方法完全多余。

解决方案

方案一:修改API支持表单数据提交

如果不需要严格使用JSON格式,直接将API的[FromBody]替换为[FromForm],接口即可直接接收表单提交的数据:

[HttpPost("LoginUser")]
[AllowAnonymous]
public async Task<ActionResult<UserLoginResponse>> LoginUserAsync([FromForm] UserLoginRequest request)
{
    var result = await authService.LoginUserAsync(request);
    return result;
}

此方案无需修改前端表单代码,直接提交即可正常工作。

方案二:AJAX提交JSON格式数据(符合API设计习惯)

若要保留API的[FromBody]要求,需通过JavaScript拦截表单提交,将数据转为JSON格式发送:

  1. 修改HTML表单(移除多余路由属性,或保留但阻止默认提交):
<form method="post" id="form">
    <div class="form-group f">
        <label for="InputUsername">Username</label>
        <input type="text" class="form-control" name="username" placeholder="Username" id="InputUsername">
    </div>
    <div class="form-group f">
        <label for="InputPassword">Password</label>
        <input type="password" class="form-control" name="password" placeholder="Password" id="InputPassword">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
  1. 添加JavaScript提交逻辑:
document.getElementById('form').addEventListener('submit', async function(e) {
    e.preventDefault(); // 阻止表单默认提交
    
    // 收集表单数据
    const loginData = {
        username: document.getElementById('InputUsername').value,
        password: document.getElementById('InputPassword').value
    };
    
    try {
        const response = await fetch('/api/Auth/LoginUser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginData)
        });
        
        const result = await response.json();
        // 处理返回结果,比如存储JWT Token、跳转页面等
        console.log(result);
    } catch (err) {
        console.error('登录失败:', err);
    }
});

注意:请删除Razor页面中多余的OnPost方法,无需通过Razor页面中转请求。

内容的提问来源于stack exchange,提问作者Uğurcan Ekici

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 20:51:23