Angular API request to .NET 5 API – net::ERR_CONNECTION_REFUSE

Issue

Intro

I am setting up an nginx server with angular universal as front-end and .NET 5 as a back-end API.

Explanation

When trying to send a post request to the API i get an net::ERR_CONNECTION_REFUSED error.
You can try it out yourself here: https://modernamedia.no/#kontakt

I have added console.logging for the error.

Error

Error:

POST http://localhost:5000/API/Contact/Contact net::ERR_CONNECTION_REFUSED
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}
headers: ro {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:5000/API/Contact/Contact: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://localhost:5000/API/Contact/Contact"

Network inspection

Error 1

Error 2

Could this possibly be a CORS issue?

Code

Angular – Contact service

export class ContactService {
  constructor(private http: HttpClient, private toast: ToastService) {}
  private SendCTAMessageURL = environment.url + '/API/Contact/Contact';
  headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  public errorMessage;
  public SendContactRequestResult = new BehaviorSubject<boolean>(false);
  SendContactRequest(model: any) {
    var request = this.http.post<any>(this.SendCTAMessageURL, model);
    var response;
    request.subscribe({
      next: (data) => {
        this.toast.Toast(
          'Melding sendt!',
          'Vi kontakter deg snarest!',
          'default',
          5000
        );
        this.SendContactRequestResult.next(true);
        response = true;
      },
      error: (error) => {
        this.errorMessage = error.message;
        console.error('There was an error!', error);
        this.toast.Toast(
          'Det oppstod en feil!',
          'Kontakt oss på tlf: 902 65 326!',
          'error',
          10000
        );
        this.SendContactRequestResult.next(false);
        response = false;
      },
    });
    return response;
  }

.NET – Startup

       public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ModernaMediaDotNet v1"));
            }
            app.ConfigureExceptionHandler(logger);
            app.UseRouting();
            app.UseCors(x => x
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .SetIsOriginAllowed(origin => true) // allow any origin
                    .AllowCredentials()); // allow credentials

            //app.UseHttpsRedirection();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

.NET – Contact Controller


namespace ModernaMediaDotNet.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ContactController : ControllerBase
    {

        private ITwillioService twillioService;
        private readonly ILoggerManager logger;

        public ContactController(ITwillioService twillioService, ILoggerManager logger)
        {
            this.twillioService = twillioService;
            this.logger = logger;
        }

        [HttpPost]
        public IActionResult Contact(ContactModel model)
        {
            string body = $"Melding fra MODERNA MEDIA: \n" +
                $"navn: {model.name} \n" +
                $"epost: {model.email} \n" +
                $"telefon: {model.phone} \n" +
                $"bedrift: {model.business} \n" +
                $"tittel: {model.title} \n" +
                $"innhold: {model.body}";
            logger.LogInfo("Initializing message");
            logger.LogInfo(body);
            try
            {
            var result = twillioService.SendMessage(body);
                return Ok(result);
            }
            catch (System.Exception e)
            {
                logger.LogError($"Something went wrong: {e}");
                return StatusCode(500, $"Internal server error: {e}");
            }
        }
    }
}

Solution

could this be a solution to your issue?

Answered By – Erik12345

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.