Adding Swagger to ASP.Net Core Web API - c#

I am trying to add Swagger to my ASP.Net Core Web API project, like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v0.1", new OpenApiInfo { Title = "My API", Version = "v0.1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v0.1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseAuthorization();
...
}
but I am getting this error:
The type or namespace name 'OpenApiInfo' could not be found
I have installed Swashbuckle.AspNetCore v4.0.1, and my project is .Net Core 3.0.

The reason it is not working is because the type OpenApiInfo comes together with the latest version of Swashbuckle.AspNetCore; open the nuget packages manager, tick the 'include prerelease' checkbox and update the package to version 5.0.0-rc3.
And then it should work.

Add the Latest version of Swashbuckle.AspNetCore package from NuGet Package Manager then it will work.

Related

CORS error after upgrade from .NET Core 3.1 to .NET 6

I recently upgraded a relatively large web API from .NET Core 3.1 to .NET 6 and am getting a no Access-Control-Allow-Origin header CORS error. I have not moved to the minimal hosting model, but I understand from the docs that this is not necessary and the old model should continue to work. I include code from startup and program below and what I had to change to make the upgraded project work. Note that everything else works properly.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod()
.WithOrigins(Configuration.GetSection("AllowedOrigins").Get<string[]>())
.SetIsOriginAllowed(origin => true)
.AllowAnyHeader();
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime appLifetime)
{
app.UseCors("CorsPolicy");
}
Note that * is returned from "AllowedOrigins".
Program.cs
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls(Configuration.GetValue<bool>("App:UsesHttps")
? $"{Configuration.GetValue<string>("App:HttpUrl")}, " +
$"{Configuration.GetValue<string>("App:HttpsUrl") }"
: $"{Configuration.GetValue<string>("App:HttpUrl")}")
.UseStartup<Startup>();
});
For the upgrade to .NET 6, nothing in Startup.cs has changed. In Program.cs, .UseUrls does not work anymore and instead I have it defined in appsettings and I have removed the call to .UseUrls.
Appsettings (.NET Core 3.1)
"App": {
"UsesHttps": false,
"HttpUrl": "http://0.0.0.0:5005",
"HttpsUrl": "https://0.0.0.0:5001"
},
Appsettings (.NET 6)
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5005"
}
}
},
Nothing else in the code has changed, and all I have done is update packages. I fail to see how they would influence a CORS error.
The app is running in a Docker container behind Nginx serving as a reverse proxy. I have not made any changed to the Nginx settings. The app is listening on HTTP only as Nginx handles the HTTPS connection. Again, this works when the app is built against .NET Core 3.1. I have read the documentation about upgrading to .NET 6 and I cannot find anything that would explain this kind of a change.
don't know if this will help you. We have the following in our API in the program.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other code left out here
app.UseAuthentication();
// Allow CORS for any origin, method or header
app.UseCors(policy =>
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthorization();
}
If I remember correctly the order of things is pretty important. I don't see Authentication and Authorization in your code. Don't know if you need that or not. There's a remark at this code as it might be allowing too much. We still have to investigate that.

GraphQL for .NET core 3.1

I'm newbie in GraphQL for .NET core.
I Added GraphQL in my source but it not into controller when debug. It went to my ObjectGrapType
See the image detail :
Click start in GrapiQL
enter image description here
Then It not go to controller
enter image description here
3.It go to the Order Query
enter image description here
I don't understand why it happens
Can't you help me check that.
Is that an error or not?
My startUp class :
public void ConfigureServices(IServiceCollection services)
{
services.AddDiscoveryClient(Configuration);
services.AddCustomDbContext(Configuration);
services.AddControllers()
.AddNewtonsoftJson(o => o.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
services.AddCustomSwagger();
services.AddCustomDependency(Configuration);
}
// 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.UseDiscoveryClient();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseGraphiQl("/graphql");
app.UseRouting();
app.UseAuthorization();
app.UseGraphQL<OrderQuerySchema>();
app.UseGraphQLPlayground(options: new GraphQLPlaygroundOptions());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Thanks very much and have a good day
LamNV
Didn't get it. what lib do you use - GraphQL.Net?
Btw, based on GraphQL.net is existed a more elegant solution that allows starting much easier. You just have to define schemas in JSON file and set DB-connection string (NReco.GraphQL)

Can I use Swashbuckle to generate Swagger UI from Blazor project c#

Can I use Swashbuckle to generate Swagger UI from project with Blazor C#
I know that swaschbuckle requires MVC and that you cannot have both of them in same project.
But is there any way around it.
I have resolved the issue by using the Balzor template for W ASP.Net core 3.0 application. And following this guide:Getting started with swashbuckle ASP.Net Core 3.0
I have used pre-release version 5.0.0-rc3 of Swashbuckle since version 4.0.1 failed at startup.
My startaup for anyone facing the same issue:
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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddSingleton<WeatherForecastService>();
}
// 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.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/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();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
Swagger is basically to expose your APIs on UI and if there is API controller concept then yes you can definitely use the swagger for blazor APIs....
Please go through the below URL and I am pretty sure that it will help you get what you want..
If you still facing any issue then please let me know I will try to give you an practical example of this...
https://www.talkingdotnet.com/create-a-crud-app-using-blazor-and-asp-net-core/

'IApplicationBuilder' does not contain a definition for 'MapAzureSignalR'

I am new to Azure Signal Services, am trying to get my application hooked to Azure Signal R services. I am doing a proof of concept, to check the feasibility to use in my application.
Code
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<NotifyHub>("notify");
});
app.MapAzureSignalR(this.GetType().FullName); ---Error code
app.UseMvc();
}
I am using .NET Core 2.2 and also added the reference to Microsoft.Azure.SignalR.AspNet version 1.0.0-preview1-10317
You need to reference the Microsoft.AspNetCore.SignalR.Http (https://dotnet.myget.org/feed/aspnetcore-ci-dev/package/nuget/Microsoft.AspNetCore.SignalR.Http) package now.
I added a reference to Microsoft.Azure.SignalR and MapAzureSignalR was available in intellisense and it compiled successfuly.
Install-Package Microsoft.Azure.SignalR -Version 1.0.6

ASP.NET MVC 6 AspNet.Session Errors - Unable to resolve service for type?

Alright, so recently I've been having a lot of trouble using the new Microsoft.AspNet.Session middleware for ASP.NET vNext (MVC 6). The error I'm getting,
Unable to resolve service for type
'Microsoft.Framework.OptionsModel.ConfigureOptions[Microsoft.AspNet.Session.SessionOptions]
while attempting to activate
'Microsoft.AspNet.Session.SessionMiddleware'
occurs on all pages regardless of session use. The DNVM version I'm using is Beta5 x86 and all the packages in the project are Beta5 as well. The project itself is an attempt at porting an ASP.NET MVC 5 project to MVC 6 without much luck. Below are links to resources that may be important:
Project.json: http://tinyurl.com/project-json
Startup.cs: http://tinyurl.com/startup-cs
It seems to be a problem with my configuration but I'm not sure what to do about it... Pls send help Dx
Unable to resolve service for type 'Microsoft.AspNetCore.Session.ISessionStore' while attempting to activate 'Microsoft.AspNetCore.Session.SessionMiddleware'
If you get this error message in ASP.NET Core, you need to configure the session services in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddSessionStateTempDataProvider();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvcWithDefaultRoute();
}
This code helps you...
In Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
....
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);//We set Time here
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvc();
}
Thanks!!!
you can add session middleware into configure method in the startup.
public void ConfigureServices(IServiceCollection services) {
services.AddSession();
services.AddMvc();
}
Step 1: Install "Microsoft.AspNetCore.Session" this package.
Step 2: Add these functions in configure services function in the startup file.
(1). services.AddSession();
(2). services.AddDistributedMemoryCache();
Step 3: Add "app.UseSession()" use session function in Configure function in the startup file.
ASP.NET CORE 6.0
In program.cs file add this
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(1800);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Then
app.UseSession();
For more Read official doc
For ASP.NET 7 there is no longer a Startup.cs file, as it is merged with the Program.cs file. Instead add
builder.Services.AddSession();
builder.Services.AddDistributedMemoryCache();
above
var app = builder.Build();
Then you can add
app.UseSession();
I am using .net core 5 . I was getting the same issue
this is how i solved it
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddMvc();
}
I have added these and I have also added these ,
I added it to the startup.cs class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
}
My problem is solved, I hope yours is solved too.
app.usesession() in the program.cs file; I deleted your method and it was fixed

Categories

Resources