Error hosting web API in Blazor server web application - asp.net-core

We have an existing .NET 5.0 Blazor web application. I have added an ASP.NET Core Web API to the same project because I want to provide a REST interface to external consumers. When I request http://localhost:5000/stripe/customerwebhook, I get a 404 not found error. What could I be missing?
My CustomerWebhookController API class looks like the following:
[Route("stripe/[controller]")]
[ApiController]
public class CustomerWebhookController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Index()
{
return Ok();
}
}
Startup.cs:
using Microsoft.AspNetCore.Mvc;
public partial class Startup
{
public void ConfigureServices(IServiceCollection services)
{
OnConfiguringServices(services);
services.AddHttpContextAccessor();
services.AddScoped<HttpClient>(serviceProvider =>
{
var uriHelper = serviceProvider.GetRequiredService<NavigationManager>();
return new HttpClient
{
BaseAddress = new Uri(uriHelper.BaseUri)
};
});
services.AddHttpClient();
services.AddAuthentication();
services.AddAuthorization();
services.AddControllersWithViews();
services.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddRazorPages();
services.AddServerSideBlazor().AddHubOptions(o =>
{
o.MaximumReceiveMessageSize = 10 * 1024 * 1024;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationIdentityDbContext identityDbContext)
{
OnConfiguring(app, env);
if (env.IsDevelopment())
{
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
app.UseDeveloperExceptionPage();
}
else
{
app.Use((ctx, next) =>
{
return next();
});
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}

Related

How to stop Hosted Blazor WASM from navigating to api

I have designed my blazor wasm application and its hosted in blazor server app, therefore both applications share the same base url. When i launch my server app, it successfully launchers the wasm app. My problem is that when i hit the refresh button on the web browser , the api/server app loads in the browser instead of refreshing the blazor web assembly. How can i stop this?
This is my Server Startup class
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddControllersWithViews();
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.ConfigureCors();
services.ConfigureIISIntegration();
services.ConfigureLoggerService();
services.ConfigureMySqlContext(Configuration);
services.ConfigureRepositoryWrapper();
services.AddAutoMapper(typeof(Startup));
services.AddControllers();
services.AddRouting(options => options.LowercaseUrls = true);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseSwagger();
//app.UseSwaggerUI();
app.UseWebAssemblyDebugging();
}
else
{
app.UseHsts();
}
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
//app.UseCors("CorsPolicy");
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All
});
app.UseRouting();
app.UseAuthorization();
app.UseMiddleware<ApiKeyMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
}
My WASM Program.cs file
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient(new AddHeadersDelegatingHandler())
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
builder.Services.AddAntDesign();
builder.Services.Configure<ProSettings>(builder.Configuration.GetSection("ProSettings"));
builder.Services.AddScoped<IChartService, ChartService>();
builder.Services.AddScoped<IProjectService, ProjectService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAccountService, AccountService>();
builder.Services.AddScoped<IProfileService, ProfileService>();
await builder.Build().RunAsync();
}
}

Where will the default _logger file be stored?

Created a sample webAPI(5.0) in asp.net core. It comes with WeatherForecastController.cs
Now this is the code :
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("entered");
var rng = new Random();
_logger.LogInformation("exited");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
I entered the _logger.LogInformation("entered");
Now where will I find this information ? will there be any file located? I am in an understanding that a file will be created and all this logging info will be stored.
this is my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddFluentValidation(s =>
{
s.RegisterValidatorsFromAssemblyContaining<Startup>();
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi", Version = "v1" });
});
services.AddDbContext<ApplicationContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly(typeof(ApplicationContext).Assembly.FullName)));
#region Repositories
services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddTransient<IDeveloperRepository, DeveloperRepository>();
services.AddTransient<IProjectRepository, ProjectRepository>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
#endregion
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi v1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
By default is it logging to the output console.
You can find more information about ASP.NET Core logging here

Form Authentication not work in ASP Net Core

I have a problem with Forms authentication in asp net core, the fact is that when the page loads, I do not see a redirect to my login URL "/Home/Login" (it s correct). Nothing is happend. Here is the code for my Startup.cs
public void ConfigureServices(IServiceCollection services)
{
string connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<EventSchedulerEntities>(options =>
options.UseSqlServer(connection));
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.SlidingExpiration = true;
options.LoginPath = $"/Home/Login";
options.Cookie.IsEssential = true;
});
services.AddAuthorization();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});
}
If anyone knows why this is happening, please help.
Controller code:
[Authorize]
public IActionResult Index()
{
return View();
}
[AllowAnonymous]
public IActionResult Login(string ReturnUrl)
{
return View();
}
Cookie, was clear before start.

Enabling basic authentication on ASP NET Core - 404

I am using this middleware as the concepts are new to me
https://github.com/blowdart/idunno.Authentication/tree/master/src/idunno.Authentication.Basic
I've implemented startup exactly as it says
However, every time I post to the WeatherForecast end point I get a 404 if the [Authorize] identifier is there. I did some reading and hence added the AuthenticationSchemes but same result
It cannot be a missing redirect, which is the other problem, as the controller is just returning content in that page?
Please can someone point me in the right direction?
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc();
services.AddRazorPages();
services.AddControllersWithViews();
services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasic(options =>
{
//options.Realm = "idunno";
options.Events = new BasicAuthenticationEvents
{
OnValidateCredentials = context =>
{
if (context.Username == context.Password)
{
var claims = new[]
{
new Claim(
ClaimTypes.NameIdentifier,
context.Username,
ClaimValueTypes.String,
context.Options.ClaimsIssuer),
new Claim(
ClaimTypes.Name,
context.Username,
ClaimValueTypes.String,
context.Options.ClaimsIssuer)
};
context.Principal = new ClaimsPrincipal(
new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
}
return Task.CompletedTask;
}
};
});
}
Then this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Controller looks like this:
[Route("[controller]")]
[Authorize(AuthenticationSchemes = idunno.Authentication.Basic.BasicAuthenticationDefaults.AuthenticationScheme)]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public ActionController<WeatherForecast> Get()
{
return Content("Authorised");
}
}
As per comment, some of the commands were in the wrong order

ASP.NET Core response compression not working

I have an endpoint that loads a json from a file and then return its contents (ASP.NET Core 2.0):
[Produces("application/json")]
[Route("api/[controller]")]
public class ReportsController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public ReportsController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpGet]
public IActionResult Get()
{
try
{
string contentRootPath = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "reports");
return Ok(System.IO.File.ReadAllText(contentRootPath + "\\teste.json"));
}
catch (Exception ex)
{
return StatusCode(500, new ResponseError(ex.Message));
}
}
}
When hitting this endpoint in Chrome, I get the following network data:
Now if I enable response compression, the size of the request gets bigger:
Here's my ConfigureServices and Configure methods:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.Providers.Add<GzipCompressionProvider>();
});
services.AddApplicationServices();
services.AddDbContext<DatabaseContext>(...);
services.AddCors();
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<DatabaseContext>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
...
});
services.AddMvc().AddJsonOptions(options => { ... });
services.AddAuthorization(options =>
{
...
});
services.AddEntityFrameworkSqlServer();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseResponseCompression();
app.UseCors(c => c.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
app.UseStaticFiles();
}
What am I missing here?