WebPage 不想与控制器 .net 7.0 一起使用

问题描述 投票:0回答:1

我有 Web 项目,首先我创建了功能的后端,并在 swagger 上对其进行了测试,一切正常,但当我尝试将其添加到我的前端时,它不起作用并且不工作不想登录或注册,这里是代码。

IAuth服务

    public interface IAuthService
    {
        Task<User> RegisterAsync(UserRequestDto request);
        Task<User> LoginAsync(UserRequestLogDto request);
    }
}

认证服务

using Microsoft.EntityFrameworkCore;
using Ryzhanovskyi.University.Tinder.Core.Interfaces;
using Ryzhanovskyi.University.Tinder.Models.Auth;
using Ryzhanovskyi.University.Tinder.Models.Models;
using Ryzhanovskyi.University.Tinder.Web.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ryzhanovskyi.University.Tinder.Core.Services
{
    public class AuthService : IAuthService
    {
        private readonly DataContext _context;
        private readonly IEmailSender _emailSender;

        public AuthService(DataContext context, IEmailSender emailSender)
        {
            _context = context;
            _emailSender = emailSender;
        }

        public async Task<User> RegisterAsync(UserRequestDto request)
        {
            if (await _context.Users.AnyAsync(u => u.Email == request.Email))
            {
                return null; 
            }

            string passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);

            var user = new User
            {
                UserName = request.Username,
                Email = request.Email,
                PasswordHash = passwordHash
            };

            var welcomeEmail = new EmailModel
            {
                Email = request.Email,
                Subject = "Mail for successfully registration at GnomeLove",
                Message = $"Welcome {user.UserName} to Dating Web APP GnomeLove, good luck in searching your love ^_^"
            };
            await _emailSender.SendEmailAsync(welcomeEmail.Email, welcomeEmail.Subject, welcomeEmail.Message);

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return user; 
        }

        public async Task<User> LoginAsync(UserRequestLogDto request)
        {
            var user = await _context.Users.FirstOrDefaultAsync(u => u.Email == request.Email);

            if (user == null)
            {
                return null;
            }

            if (!BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
            {
                return null;
            }

            return user;
        }
    }
}

验证控制器

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Ryzhanovskyi.University.Tinder.Core.Interfaces;
using Ryzhanovskyi.University.Tinder.Models.Auth;
using Ryzhanovskyi.University.Tinder.Models.Models;
using Ryzhanovskyi.University.Tinder.Core.Services;

namespace Ryzhanovskyi.University.Tinder.Web.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly IAuthService _authService;

        public AuthController(IAuthService authService)
        {
            _authService = authService;
        }

        [HttpPost("register")]
        public async Task<ActionResult<User>> Register(UserRequestDto request)
        {
            var user = await _authService.RegisterAsync(request);

            if (user == null)
            {
                return BadRequest("Email is already registered.");
            }

            return Ok(user);
        }

        [HttpPost("login")]
        public async Task<ActionResult<User>> Login(UserRequestLogDto request)
        {
            var user = await _authService.LoginAsync(request);

            if (user != null)
            {
                return user;
            }

            if (user == null)
            {
                return BadRequest("Invalid email or password.");
            }

            return Ok(user);
        }
    }
}

登录.cshtml

@page
@using Ryzhanovskyi.University.Tinder.Models.Auth
@model Ryzhanovskyi.University.Tinder.Web.Pages.Auth.LoginModel

@{
    ViewData["Title"] = "Login";
}

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6 card p-4">
            <h2 class="text-center text-info mb-4">Login</h2>

            <form asp-action="Login" method="post">
                <div asp-validation-summary="ModelOnly" class="mb-3"></div>

                <div class="mb-3">
                    <label asp-for="UserRequestLog.Email"></label>
                    <input asp-for="UserRequestLog.Email" class="form-control" />
                    <span asp-validation-for="UserRequestLog.Email" class="text-danger"></span>
                </div>

                <div class="mb-3">
                    <label asp-for="UserRequestLog.Password"></label>
                    <input type="password" asp-for="UserRequestLog.Password" class="form-control" />
                    <span asp-validation-for="UserRequestLog.Password" class="text-danger"></span>
                </div>

                <div class="d-flex justify-content-between align-items-center">
                    <a href="Register" class="text-decoration-none">Don't have an account?</a>
                    <input type="submit" value="Login" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
</div>

@section Scripts{
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}

登录.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Ryzhanovskyi.University.Tinder.Core.Interfaces;
using Ryzhanovskyi.University.Tinder.Models.Auth;

namespace Ryzhanovskyi.University.Tinder.Web.Pages.Auth
{
    public class LoginModel : PageModel
    {
        private readonly IAuthService _authService;

        public LoginModel(IAuthService authService)
        {
            _authService = authService;
        }

        [BindProperty]
        public UserRequestLogDto UserRequestLog { get; set; }

        public async Task<IActionResult> LoginAsync()
        {
            if (ModelState.IsValid)
            {
                var result = await _authService.LoginAsync(UserRequestLog);

                if (result != null)
                {
                    return RedirectToPage("/main");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Wrong Password or Account with this email doesn't exist");
                    return Page();
                }
            }

            return Page();
        }
    }
}

我做了很多尝试,但我首先使用.net,因为我的 Eleks 老师希望我们在 .net 上创建一个 Web 项目,但显然没有任何东西教我们如何做。

c# asp.net-core razor .net-7.0
1个回答
0
投票

首先,您在测试 Api 时提到“在 Swagger 中一切正常”,因此我们可以说控制器和服务应该运行良好。然后你分享了

Login.cshtml
Login.cshtml.cs
,我们将
private readonly IAuthService _authService;
注入到
Login.cshtml.cs
中,这样我们就可以说我们现在没有使用 API,我们只使用 IAuthService。

所以我创建了一个razor page web应用程序并进行了测试,我将html内容复制并粘贴到我的index.cshtml中,这次当我单击登录按钮时,我们将发送一个post请求

https://localhost:7252/?action=Login
,这不会点击
public async Task<IActionResult> LoginAsync()
方法,我将方法名称改为
OnPostAsync
后,就可以触发该功能了。然后 AuthService 就可以开始工作了。

让我们回到错误消息,415 错误意味着不支持的媒体,这是此错误的高票示例。但我在你分享的代码中没有看到相关设置。恐怕我们缺乏重现该问题的信息。我的测试代码如下。顺便说一句,由于您正在尝试创建登录模块,因此您还可以使用包含开箱即用页面和数据库表的默认 asp.net core 身份。您可以通过 VS 2022 模板创建一个新的 .net 7 Web 应用程序,并在选择 .net 版本后选择

Individual Account
作为身份验证类型。

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WebApp.Models;
using WebApp.Services;

namespace WebApp.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IAuthService _authService;


        public IndexModel(ILogger<IndexModel> logger, IAuthService authService)
        {
            _logger = logger;
            _authService = authService;
        }

        [BindProperty]
        public UserRequestLogDto UserRequestLog { get; set; }

        public void OnGet()
        {

        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var result = _authService.LoginAsync(UserRequestLog);

                if (result != null)
                {
                    return RedirectToPage("/privacy");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Wrong Password or Account with this email doesn't exist");
                    return Page();
                }
            }

            return Page();
        }

    }
}


@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6 card p-4">
            <h2 class="text-center text-info mb-4">Login</h2>

            <form asp-action="Login" method="post">
                <div asp-validation-summary="ModelOnly" class="mb-3"></div>

                <div class="mb-3">
                    <label asp-for="UserRequestLog.Email"></label>
                    <input asp-for="UserRequestLog.Email" class="form-control" />
                    <span asp-validation-for="UserRequestLog.Email" class="text-danger"></span>
                </div>

                <div class="mb-3">
                    <label asp-for="UserRequestLog.Password"></label>
                    <input type="password" asp-for="UserRequestLog.Password" class="form-control" />
                    <span asp-validation-for="UserRequestLog.Password" class="text-danger"></span>
                </div>

                <div class="d-flex justify-content-between align-items-center">
                    <a href="Register" class="text-decoration-none">Don't have an account?</a>
                    <input type="submit" value="Login" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
</div>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.