Daer Developers,
I have .net core web api, and I have angualr client.
Now I am trying to call the web api from angualr ?
Here is my web api programme class ?
public class Startup
{
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.AddCors();
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddCors(options =>
{
options.AddPolicy(name: "AllowOrigin", bulider =>
{
bulider.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod();
});
});
services.AddDbContext<UserContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDBConnection")));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1"
});
});
services.AddControllers();
services.AddCors();
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
services.AddCors(options =>
{
options.AddPolicy(
"CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseCors(options =>options.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod());
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Here is my angualr project api call.
const options =
{headers:
{'Content-Type': 'application/json',"Access-Control-Allow-Origin":"*"},
};
this.http.post<null>("http://localhost:55768/api/CreateUser",
JSON.stringify({FirstName: User.FirstName,
LastName: User.LastName,
Email: User.Email,
Mobile: User.Mobile,
Gender: User.Gender,
Pwd: User.Pwd}), options).subscribe(
(t: null) => console.info(JSON.stringify(t))
);