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

Vue向ASP.NET Core MVC(集成Identity)发送登录POST请求时返回400错误的问题求助

Vue向ASP.NET Core MVC(集成Identity)发送登录POST请求时返回400错误的问题求助

大家好,我现在碰到一个头疼的问题:在Vue项目的views文件夹下有个LoginView.vue子页面,我想通过它调用ASP.NET Core MVC项目里基于Identity实现的登录接口,但发送POST请求时一直返回400 Bad Request,我可以百分百确认登录信息是正确的,而且已经在ASP.NET Core MVC那边配置了CORS来解决跨域问题,但还是没解决。

下面是我的代码和错误信息:

Vue项目:LoginView.vue代码

<template>
    <div>
        <h2>Hello</h2>
        <hr />
        <div class="form-floating mb-3">
            <input v-model="email" type="email" class="form-control" autocomplete="username" aria-required="true" />
            <label for="email" class="form-label">Email</label>
        </div>
        <div class="form-floating">
            <input v-model="password" type="password" class="form-control" autocomplete="current-password"
                aria-required="true" />
            <label for="password" class="form-label">Password</label>
        </div>
        <div class="form-check">
            <input v-model="rememberMe" type="checkbox" class="form-check-input" id="rememberMe" />
            <label class="form-check-label" for="rememberMe">Remember Me</label>
        </div>
        <button @click="login" type="button" class="w-100 btn btn-lg btn-primary">Log in</button>
    </div>
</template>

<script>
import axios from 'axios';

const API_URL = "http://localhost:5211/";

export default {
    data() {
        return {
            email: '',
            password: '',
            rememberMe: false
        };
    },
    methods: {
        login() {
            const loginData = {
                email: this.email,
                password: this.password,
                rememberMe: this.rememberMe
            };

            axios.post(API_URL + 'identity/Account/Login', loginData)
                .then(response => {
                    console.log('Login response:', response.data);

                    console.log("Email:", this.email);
                    console.log("Password:", this.password);
                })
                .catch(error => {
                    console.error('Error during login:', error);
                });
        }
    }
}
</script>

<style scoped></style>

ASP.NET Core MVC项目:LoginModel代码(注:原标注为Program.cs,实际是Account/Login页面的后台逻辑代码)

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using AuthProject.Areas.Identity.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace AuthProject.Areas.Identity.Pages.Account
{
    public class LoginModel : PageModel
    {
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly ILogger<LoginModel> _logger;

        public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger)
        {
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public string ReturnUrl { get; set; }

        [TempData]
        public string ErrorMessage { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public bool RememberMe { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            if (User.Identity.IsAuthenticated)
            {
                Response.Redirect("/");
            }

            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            returnUrl ??= Url.Content("~/");

            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }

                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }

                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            return Page();
        }
    }
}

错误信息

点击登录按钮后,浏览器控制台返回:

POST http://localhost:5211/identity/Account/Login 

400 (Bad Request)
@LoginView.vue:44
_createElementVNode.onClick._cache.._cache.
@LoginView.vue:18

对应的代码行:

  • LoginView.vue第43行:axios.post(API_URL + 'identity/Account/Login', loginData)
  • LoginView.vue第18行:<button @click="login" type="button" class="w-100 btn btn-lg btn-primary">Log in</button>

另外还有一个错误详情截图:
请求错误详情

希望各位能帮我看看问题出在哪,谢谢大家!

备注:内容来源于stack exchange,提问作者Łukasz Glienke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 12:48:00