API Rest ASP.Net Core 3.1 returning 404 error when published

Asked

Viewed 1,132 times

0

I’m doing some testing with Apis in ASP.Net Core 3.1. In this case, I am using Entity Framework to access the database and Identity Core to register and log in users.

To do so, I have implemented the following controller:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
    private readonly UserManager<IdentityUser> _userManager;
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly IConfiguration _configuration;

    public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, IConfiguration configuration)
    {
        this._userManager = userManager;
        this._signInManager = signInManager;
        this._configuration = configuration;
    }

    [HttpGet]
    public string Get()
    {
        return $"AccountController :: {DateTime.Now.ToShortDateString()}";
    }

    [HttpPost("Login")]
    public async Task<ActionResult<UserToken>> Login([FromBody] UserInfo userInfo)
    {
        var result = await _signInManager.PasswordSignInAsync(userInfo.Email, userInfo.Password, isPersistent: false, lockoutOnFailure: false);

        if (result.Succeeded)
        {
            return await GenerateTokenAsync(userInfo);
        }
        else
        {
            return BadRequest(new { message = "Login inválido" });
        }
    }

I also have the method of registration in this controller, but this does not come to the case.

The problem I need help with: in development mode, all services work (login, registration and a test Get, which return only one string, accessed in "api/Account"). However, when I publish my project, only this Get test service works. When I try to access the login API, I get a 404 reply Not found.

If you make a difference, here is the login method call:

@inject HttpClient http
@inject NavigationManager navigation
@inject TokenAuthenticationProvider authStateProvider
async Task FazerLogin()
{
    try
    {
        var loginAsJson = JsonSerializer.Serialize(userInfo);

        var httpResponse = await http.PostAsync("api/account/login", new StringContent(loginAsJson, Encoding.UTF8, "application/json"));

        if (httpResponse.IsSuccessStatusCode)
        {
            var responseAsString = await httpResponse.Content.ReadAsStringAsync();

            var loginResult = JsonSerializer.Deserialize<UserToken>(responseAsString, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            await authStateProvider.Login(loginResult.Token);
            navigation.NavigateTo("/");
        }
        else
        {
            loginFalhou = true;
            Mensagem = $"Não foi possível realizar o login do usuário. (Erro: {httpResponse.StatusCode})";
        }
    }
    catch (Exception)
    {
        loginFalhou = true;
        Mensagem = $"Não foi possível realizar o login do usuário...";
    }

}

I used the Postasync method to check if the request was successful. But I also tried to implement the login call this way:

async Task FazerLogin()
{
    try
    {
        var loginResult = await http.PostJsonAsync<UserToken>("/api/account/login", userInfo);

        await authStateProvider.Login(loginResult.Token);
        navigation.NavigateTo("/");
    }
    catch (Exception ex)
    {
        Console.Write(ex);
    }
}

The error always remains.

Error occurring when login service call using HttpClient.

The only difference I notice between services is that the service that works returns only one string. Login, registration and other controllers return a Task>. Is this the problem? If so, is there another way to implement login?

  • Debug your code and locate exactly where you are getting the 404, wouldn’t be here? await http.PostAsync("api/account/login??? Are you sure you are serving the application at port 91?

  • Yes, it is in this location that the error occurs. However, debugging the code does not occur the error. It only occurs when published and hosted (in production). And yes, I’m sure I’m serving the application on port 91, because when I require the GET/api/Account service I get a successful response. Error occurs by calling POST /api/Account/login.

  • you noticed that your post is for "api/... and not to "/api/..."

  • Just in the example where I used http.Postasync, in the example where I used http.Postjsonasync is /api/.... But this does not influence, the Httpclient library solves the URL. As I commented earlier, the curious thing is that if I request the GET/api/Account service from Postman, I succeed in the request. Error 404 only receive when I require POST /api/Account/login...

  • In any case, I was able to solve the problem. I circumvented the login service with a Try catch and started to return the stacktrace. With that I noticed that the error was in the connecion string. In development mode do not need to pass the login and password of the bank, but in production this is required. Thank you for the attention =D

  • So I guess that question can be closed ;)

  • The page it exists on the server, the return of your method returns to a page exists on the server?

Show 2 more comments

1 answer

0


I solved the problem. I circled the login service with Try catch and started returning the stacktrace. With this I noticed that the error was in the connection string, because I had not informed the login and password of the database. After all, in the development mode it is not necessary to enter the login and password of the database, but in production this is mandatory. Thank you all for the tips = D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.