0

I am trying to learn how to send an http post request to my api service using Http (not Http Client) but the request is not even received.

URL is correct and so is the API name (they matches)...

From the first analysis made in the comments with some kind users, it looks like the problem is somehow related to the API server, which is unreachable and seems to not exist.

Can you please tell me what I am doing wrong?

Here's my code.

REGISTRATION COMPONENT .ts method (which calls the USER SERVICE):

registerUser({ value, valid }: { value: UserRegistration, valid: boolean }) {
    this.submitted = true;
    this.isRequesting = true;
    this.errors='';
    if(valid)
    {
        this.userService.register(value.email,value.password,value.firstName,value.lastName,value.location)
                  .finally(() => this.isRequesting = false)
                  .subscribe(
                    result  => {if(result){
                        this.router.navigate(['/login'],{queryParams: {brandNew: true,email:value.email}});                         
                    }},
                    errors =>  this.errors = errors);
    }      
 } 

USER SERVICE .ts (called by REGISTRATION COMPONENT):

register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> {
let body = JSON.stringify({ email, password, firstName, lastName,location });
let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    console.log(this.baseUrl); //URL is correct

return this.http.post(this.baseUrl + "/Accounts/NewUser", body, options)
  .map(res => true)
  .catch(this.handleError);
 }  

API Method

[Route("api/[controller]")] 
public class AccountsController : Controller
{
    //...
    // POST api/Accounts/Newuser
    [HttpPost("NewUser")]
    public async Task<IActionResult> NewUser([FromBody]RegistrationViewModel model)
    {
         //....

As requested:

NETWORK CHROME TAB

Network

HEADERS DETAILS

Headers

Where preview show "Failed to load response data"

CONSOLE ERROR:

Error


as requested:

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using MyFirstAngularApp.Data;
using MyFirstAngularApp.Models;
using MyFirstAngularApp.Auth;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using MyFirstAngularApp.Helpers;
using MyFirstAngularApp.Models.Entities;
using Microsoft.AspNetCore.Identity;
using System.Text;
using AutoMapper;
using FluentValidation.AspNetCore;

namespace MyFirstAngularApp
{
    public class Startup
    {
        private const string SecretKey = //MY SECRET KEY
        private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            //connecting to database
            var connectionString = //MY CONNECTION STRING
            services.AddDbContext<MyDataContext>(options => options.UseSqlServer(connectionString));

            //connect to authentication database
            var connectionEntityString = //ANOTHER CONNECION STRING
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionEntityString));

            //managing tokens
            services.AddSingleton<IJwtFactory, JwtFactory>();

            services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();

            // jwt wire up
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure<JwtIssuerOptions>(options =>
            {
                options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _signingKey,

                RequireExpirationTime = false,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            // api user claim policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
            });

            // add identity
            var builder = services.AddIdentityCore<AppUser>(o =>
            {
                // configure identity options
                o.Password.RequireDigit = false;
                o.Password.RequireLowercase = false;
                o.Password.RequireUppercase = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength = 6;
            });
            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

            services.AddAutoMapper();
            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
    }
}
0

2 Answers 2

1

Lets you try that as Configure in startup class

      if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

  app.UseExceptionHandler(
  builder =>
  {
    builder.Run(
            async context =>
            {
              context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
              context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

              var error = context.Features.Get<IExceptionHandlerFeature>();
              if (error != null)
              {
                await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
              }
            });
  });

  app.UseDefaultFiles();
  app.UseStaticFiles();
  app.UseMvc();
Sign up to request clarification or add additional context in comments.

Comments

0

There were two problems in my code and app below:

The first is that I wasn't using the startup.cs configuration suggested by user Stefan in his answer.

The second one was that I was passing a static port address to my URL.
I've solved by using this._apiURI = '/api'; instead of this._apiURI = 'http://localhost:5000/api'; in my service module as suggested by user Deadpool in the comments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.