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

ASP.NET Web API端点URL配置及前端Fetch请求错误排查

问题分析与修复方案

你的代码存在三个核心问题,导致接口调用失败:

1. 请求方法不匹配

ASP.NET接口标记的是[HttpGet("get-user-by-id")],但JavaScript中使用的是POST请求方法,这会直接触发405 Method Not Allowed错误。

2. 参数传递方式错误

HttpGet方法的参数默认从URL查询字符串中获取,但你把email和password放在了请求Body里,ASP.NET无法解析这些参数,会导致参数值为null,进而返回NotFound。

3. URL格式错误

JavaScript中的URL包含多余的双引号:'https://"mylocalhost"/api/User/get-user-by-id',这会导致请求地址无效,需要去掉双引号,替换为实际的本地服务地址(比如https://localhost:5001)。


推荐修复方案(改用POST请求,更安全)

登录涉及敏感信息,用GET会把密码暴露在URL中,建议将接口改为POST:

修改ASP.NET接口代码

[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    // 改为HttpPost,路由用login更符合语义
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest request)
    {
        var result = await _userService.GetUser(request.Email, request.Password);

        if (result == null) return NotFound();

        return Ok(result);
    }
}

// 新增参数接收模型
public class LoginRequest
{
    public string Email { get; set; }
    public string Password { get; set; }
}

修改JavaScript请求代码

// 替换mylocalhost为实际本地服务地址,比如https://localhost:5001
fetch('https://mylocalhost/api/User/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ email, password }),
})
.then(function (response) {
    if (!response.ok) {
        throw new Error('HTTP error! Status: ' + response.status);
    }
    return response.json();
})
.then(function (data) {
    console.log('Login success:', data);
    window.location.href = 'profile.html';
})
.catch(function (error) {
    console.error('Login error:', error.message);
    if (error.message.includes('401')) {
        console.log('Incorrect username or password');
    } else {
        console.log('An error occurred during login');
    }
});

备选方案(保持GET请求,不推荐)

如果坚持使用GET,需要把参数放到查询字符串中:

// 用模板字符串拼接查询参数,注意编码防止特殊字符问题
fetch(`https://mylocalhost/api/User/get-user-by-id?email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}`, {
    method: 'GET',
})
.then(function (response) {
    if (!response.ok) {
        throw new Error('HTTP error! Status: ' + response.status);
    }
    return response.json();
})
.then(function (data) {
    console.log('Login success:', data);
    window.location.href = 'profile.html';
})
.catch(function (error) {
    console.error('Login error:', error.message);
    if (error.message.includes('401')) {
        console.log('Incorrect username or password');
    } else {
        console.log('An error occurred during login');
    }
});

额外注意:跨域问题

如果前端页面和API服务不在同一域名/端口下,需要在ASP.NET中配置CORS:

在Program.cs中添加:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
    {
        // 替换为你的前端地址,比如http://localhost:3000
        policy.WithOrigins("http://localhost:3000")
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// 在UseRouting之后添加
app.UseCors("AllowFrontend");

内容的提问来源于stack exchange,提问作者wngm_889

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:01:01