I am working the Microsoft Learn tutorials to "Create a web API with ASP.Net Core".
I used .NET5
I have a problem when I run the command:
httprepl connect http://localhost:5000
I am getting a response, "Unable to find an OpenAPI description".
And the following command "ls" returns me from it not trooping endpoints.
c:/xxx/Source/Repos/ContosoPizza
$ httprepl http://localhost:5000
(Disconnected)> connect http://localhost:5000
Using a base address of http://localhost:5000/
Unable to find an OpenAPI description
For detailed tool info, see https://aka.ms/http-repl-doc
http://localhost:5000/> ls
No directory structure has been set, so there is nothing to list. Use the "connect" command to set a directory structure based on an OpenAPI description.
I tried all the solutions offered by #Gowiser in the question launched by #Nuse Why is HttpRepl unable to find an OpenAPI description? The command "ls" does not show available endpoints
But nothing worked.
Working through Create a web API with ASP.NET Core Controllers i also did run into the error
Unable to find an OpenAPI description
The tutorial uses dotnet 6, i was using dotnet core 3.1.
I did the changes from sasha answers here and had to add these packages
dotnet add package Microsoft.OpenApi --version 1.2.3
dotnet add package Swashbuckle.AspNetCore.Swagger --version 6.2.3
dotnet add package Swashbuckle.AspNetCore.SwaggerUI --version 6.2.3
dotnet add package Swashbuckle.AspNetCore.SwaggerGen --version 6.2.3
After all that i still got error messages. In step 4 of Exercise - Create a web API project the following is written
Connect to our web API by running the following command:
httprepl https://localhost:{PORT}
Alternatively, run the following command at any time while the HttpRepl is running:
(Disconnected)> connect https://localhost:{PORT}
I was not aware that running httprepl like this
httprepl https://localhost:{PORT}
still requires that your web app is running. So you have to open a second terminal (cmd.exe) to run your webapi project dotnet run. After that you can connect to the swagger docs using httprepl like this
connect http://localhost:5000 --verbose --openapi /swagger/v1/swagger.json
http://localhost:5000/> ls
. []
WeatherForecast [GET]
http://localhost:5000/> cd WeatherForecast
/WeatherForecast [GET]
http://localhost:5000/WeatherForecast> get
HTTP/1.1 200 OK
This did the trick for me.
Adding the swagger ui
Swashbuckle.AspNetCore - Getting Started contains
Optionally, insert the swagger-ui middleware if you want to expose
interactive documentation, specifying the Swagger JSON endpoint(s) to
power it from.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "My API V1");
});
If you change startup.cs to include this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ContosoPizza v1"));
}
....
You get a nice gui under http://localhost:5000/swagger/ which looks like this
I am assuming you are following the steps described in the 'Create a web API project' exercise of the Create a web API with ASP.NET Core course.
Before going through step 5. make sure in your project there is:
a services.AddSwaggerGen() call in the Startup.ConfigureServices() method
an app.UseSwagger() call in the Startup.Configure() method
Here is a working version of Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
namespace ContosoPizza
{
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.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ContosoPizza", Version = "v1" });
});
}
// 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", "ContosoPizza v1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Calling ls in the httprepl session shows expected results:
❯ httprepl http://localhost:5000
(Disconnected)> connect http://localhost:5000
Using a base address of http://localhost:5000/
Using OpenAPI description at http://localhost:5000/swagger/v1/swagger.json
For detailed tool info, see https://aka.ms/http-repl-doc
http://localhost:5000/> ls
. []
WeatherForecast [GET]
http://localhost:5000/>
Here you can find a full project for this exercise.
Indeed #surfmuggle to connect to the API via httprepl, the API had to be running in another terminal, so 2 terminals in total:
1 to run the API with dotnet run
1 other to call instructions like ls or other later
run this command first:
dotnet dev-certs https --trust
Related
I am attempting to setup a simple solution that consists of a ASP.NET Core 6 Web Api project and a .NET Core class library project using EF Core 7 and running into problems setting up the DBContext in the Program.cs file and running EF migrations.
Here is a copy of my Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Web;
using MyEFCoreTestProject.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
builder.Services.AddDbContext<MyDbContext>(
options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Here is a copy of my DBContext in the other project.
using Core;
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
public DbSet<Customer> Customers{ get; set; }
public DbSet<CustomerAddress> CustomerAddresses { get; set; }
}
In my class library project where the DBContext exists I have the following nuget packages installed:
Microsoft.EntityFrameworkCore 7.0.2
Microsoft.EntityFrameworkCore.Design 7.0.2
Microsoft.EntityFrameworkCore.Relational 7.0.2
Microsoft.EntityFrameworkCore.SqlServer 7.0.2
Microsoft.EntityFrameworkCore.Tools 7.0.2
No matter how I attempt to run the migration I get the following error:
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'MyDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyEFCoreTestProject.MyDbContext]' while attempting to activate 'MyEFCoreTestProject.MyDbContext'.
This is just what I have been running into while trying to do what I believe is a simple dependency registration. What I really would like to do is create a DbContext with a constructor that allows me to pass the connection string and some other flags in as parameters but my first step is just to get things working so I will have to tackle that next after this issue is solved.
Also I am not opposed to a DbContextFactory but I have been unable to find a working example that I could follow in .Net Core 6.
Any help anyone could provide is greatly appreciated.
I am trying to setup honeycomb in my .net sample app with .net 6.
https://docs.honeycomb.io/getting-data-in/opentelemetry/dotnet-distro/#initialize
I am getting an error when I run my code with the below exception:
System.MissingMethodException: 'Method not found: 'OpenTelemetry.Trace.TracerProviderBuilder OpenTelemetry.Trace.TracerProviderBuilderExtensions.ConfigureBuilder(OpenTelemetry.Trace.TracerProviderBuilder, System.Action`2<System.IServiceProvider,OpenTelemetry.Trace.TracerProviderBuilder>)'.'
Below is my program.cs file
using Microsoft.EntityFrameworkCore;
using ProductCRUDAPI.Models;
using OpenTelemetry.Trace;
using OpenTelemetry;
using Honeycomb.OpenTelemetry;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DB");
builder.Services.AddDbContextPool<DbContext>(option => option.UseSqlServer(connectionString));
// Add services to the container.
var honeycombOptions = builder.Configuration.GetHoneycombOptions();
builder.Services.AddControllers();
builder.Services.AddOpenTelemetry().WithTracing(configure: otelBuilder =>
otelBuilder
.AddHoneycomb(honeycombOptions)
.AddAspNetCoreInstrumentationWithBaggage()
).StartWithHost();
builder.Services.AddSingleton(TracerProvider.Default.GetTracer(honeycombOptions.ServiceName));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
I am trying to setup honeycomb in my .net sample app for testing using the below guide
https://docs.honeycomb.io/getting-data-in/opentelemetry/dotnet-distro/#initialize
Was expecting to get the connection to go through and the logger to initialize successfully so I can attach it to my endpoints.
Just experienced this error myself, there's a package missing, go to the NUGet Package Manager in Visual Studio, checked the "include prerelease" box and then install the
OpenTelemetry.Instrumentation.AspNetCore
prerelease package.
Honeycomb have fairly recently upgraded their OpenTelemetry package from prerelease, but it seems some other dependencies are required from OpenTelemetry packages still in prerelease, some issues like these may keep occurring until all the dependent packages are out of prerelease and development stabilises a bit!
I'm fumbling through my first exploration into docker containers with .NET. My local development environment is good to go - I've got my dev certs created and specified in my configuration file.
However, I'm trying to deploy to Azure Container Instances using a Caddy sidecar as a reverse-proxy. My application container fails on startup with the error: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date.
As far as I understand, I'll still need Kestrel, however the incoming traffic is no longer required to be HTTPS since it's being routed internally through the reverse-proxy.
I've tried tampering with my Startup.cs and Program.cs files to no avail. Can anyone point me in the right direction? Thanks.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc(options => { options.EnableEndpointRouting = false; });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app
.UseStaticFiles()
.UseHsts()
.UseHttpsRedirection()
.UseMvc(routes => routes.MapRoute(name: "default", template: "{controller=App}/{action=Index}/{id?}"));
}
Program.cs
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel();
})
.ConfigureAppConfiguration(cb => { cb.AddEnvironmentVariables(); });
When the developer certs seems to had expired,
you can try running these
but initially Close your browsers so that they do not cache the certificates
On the commandline run
dotnet dev-certs https –clean
then run
dotnet dev-certs https -t a single time to create and trust a new development certificate.
Then please check the certificate with dotnet dev-certs https –verbose
and Restart VS
Reference: Unable to configure HTTPS endpoint- Wayne Thompson
You can try removing app.UseHttpsRedirection(); and adding UseHsts() as the way as you mentioned .
References:
Also please check this SO reference where kestrel configuration with urls is made.
docker - Unable to configure HTTPS endpoint for .net Core Kestral Server in Linux Container on Azure - Stack Overflow
I've been struggling for these 2 days.
Does anyone know what's the problem? I tried to publish my .net core API to IIS, but always failed when browse the web.
I did the step to publish same as like this webpage.
After I browse on the server, http://127.0.0.1:5100/swagger/index.html , the page said No webpage was found. I am sure there no system/apps using the 5100 port.
After I browse on the server, http://127.0.0.1:5100/swagger/index.html , the page said No webpage was found.
If you check the code of Configure method in Startup.cs, you can find the app will only serve the Swagger UI on Development environment.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAppi v1"));
}
If you'd like to serve the Swagger UI on Production environment after you publish it on IIS, you can modify the code as below, then republish it to IIS.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAppi v1"));
//...
Besides, if your IIS site is just for testing purpose, to quickly resolve the issue and make your site show the Swagger UI as expected, you can try to add an environment variable as below for your site.
Very simple ASP .NET core application so far. I've turned on the developer exception page as follows
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDeveloperExceptionPage();
app.UseMvc();
}
I've deployed it on windows as a portable app and i'm able to see the errors on the developer page (awesome page by the way) when a specific web API request fails with an exception.
I publish the same app to Ubuntu as a self-contained app and I don't get the developer error page to show up (though the seems to run fine - i've hard coded an error just to test the developer page itself).
By default on macOS and Linux ASP.NET Core's Hosting environment is Production.
On Ubuntu you can start the application and set the Hosting environment from command line using
> dotnet run --environment=Development
For macOS:
$ ASPNETCORE_ENVIRONMENT=Development dotnet run
If you are using Visual Studio Code, in launch.json there's the following setting for each configuration:
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
The Developer Exception Page is for use when the environment is Development.
See https://www.exceptionnotfound.net/working-with-environments-and-launch-settings-in-asp-net-core/
The act of publishing the app to Ubuntu is setting the environment to Production.
This is the behavior I found: (ASP.NET Core version 6, on Windows)
When environment is Development, exception pages are always generated, regardless of whether UseDeveloperExceptionPage was called.
When environment is anything other than Development, exceptions pages are generated only if UseDeveloperExceptionPage was called.
Startup.cs is mostly procedural. In your Startup.cs
app.UseDeveloperExceptionPage();
should come before
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
If you add it after then it won't function.