如何修复HttpErrorResponse 404找不到

时间:2019-05-09 00:56:08

标签: c# angular

我在Web控制台上收到错误消息,它显示“ http://localhost:5000/api/authregister的Http错误响应:404未找到”。我尝试在线寻找解决方案,但没有帮助。如何解决此问题?

pic1

我试图查看Postman是否与“ GET”一起使用,并且确实起作用,但是在“ POST”上,它将不会更新数据库并且没有响应。

pic2

我检查了数据库的更新结果,但没有任何变化,我那里只有2个用户名和密码:

pic3

更新:我找到了获得此IP地址的原因:

  

http://localhost:5000/api/authregister

在baseUrl上,我在 auth.service.ts 上缺少'/',但是现在我收到“ http://localhost:5000/api/auth/register的Http失败响应:400错误的请求”。这是 auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {map} from'rxjs/operators';

@Injectable({ //inject to service
  providedIn: 'root'
})
export class AuthService {
  baseUrl = 'http://localhost:5000/api/auth/'; //I added a '/' to the end

constructor(private http: HttpClient) { }

login(model: any) {
  return this.http.post(this.baseUrl + 'login', model)
  .pipe(
    map((response: any) => {
      const user = response;
      if (user) {
        localStorage.setItem('token', user.token);
      }
    })
  )
}

register(model: any) { //need authservice in register component constructor
  return this.http.post(this.baseUrl + 'register', model);
  //return this.http.post(this.baseUrl + 'auth/register', model);
}


}

这是AuthController.cs

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using DatingApp.API.Data;
using DatingApp.API.Dtos;
using DatingApp.API.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens; //Symmetric Security Keys

namespace DatingApp.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
    private readonly IAuthRepository _repo;
    private readonly IConfiguration _config;
    public AuthController(IAuthRepository repo, IConfiguration config)
    {
        _config = config;
        _repo = repo;
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(UserForRegisterDto userForRegisterDto) //get username and password, [FromBody] gives hint where info is
    {
        userForRegisterDto.Username = userForRegisterDto.Username.ToLower(); //make username lowercase

        if (await _repo.UserExists(userForRegisterDto.Username)) //check if User exist
            return BadRequest("Username already exist"); //BadRequist requires ControllerBase

        var userToCreate = new User
        {
            Username = userForRegisterDto.Username //APIModels
        };

        var createdUser = await _repo.Register(userToCreate, userForRegisterDto.Password);

        return StatusCode(201);
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(UserForLoginDto userForLoginDto)
    {
        //throw new Exception("Computer says no!");

        var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

        if (userFromRepo == null)
            return Unauthorized();

        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), //token claims Id
            new Claim(ClaimTypes.Name, userFromRepo.Username) //token claims username
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8
        .GetBytes(_config.GetSection("AppSettings:Token").Value)); //MUST set TOKEN in appsettings.json

        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.Now.AddDays(1),
            SigningCredentials = creds
        };

        var tokenHandler = new JwtSecurityTokenHandler(); //to make token

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return Ok(new {
            token = tokenHandler.WriteToken(token)
        });
    }


}
}

1 个答案:

答案 0 :(得分:2)

根据您的Controller代码,您的api路由为api/auth/register,因此您只缺少/。将其更改为呼叫http://localhost:5000/api/auth/register,您应该会更幸运。

为澄清起见,当您将其放在控制器中时:[Route("api/[controller]")]它告诉路由,该控制器中的每个端点都将从路由api/auth开始(换句话说,[controller]表示控制器名称中Controller单词之前的部分。

当您随后用[HttpPost("register")]标记端点方法时,它告诉路由引擎您希望在将POST附加到路由末尾的端点上接收/register请求对于那个控制器。

因此,换句话说api/auth/register将执行public async Task<IActionResult> Register(UserForRegisterDto userForRegisterDto)方法。

如果您检查ValuesController,则可能会在控制器顶部看到相同的属性标签,告诉它使用路由api/values,但是当您到达get方法时,它可能具有[HttpGet]的属性,它告诉它对GET的任何api/values请求都应该执行该方法。不需要添加任何路径。

有道理吗?