services.AddSwaggerGen() giving error - c#

All I'm trying to do is add swagger to an ASP.Net Core application. I'm watching a tutorial and all I see them do is add services.AddSwaggerGen(); under the configure services area in the Startup.cs file. Like any normal service like MVC... But I get an error:
There is no argument given that corresponds to the required formal parameter 'setupAction'...
I don't see anyone supplying any kind of argument to services.AddSwaggerGen() so does anyone know what I'm missing here?
I've added the SwashBuckler.AspNetCore dependency so swagger is in the application. Just don't know why it's red and giving the above error.

I had problem, that
IServiceCollection does not contain a definition for 'AddSwaggerGen'
I turnes out, that I installed Swashbuckle.AspNetCore.Swagger nuget package instead of Swashbuckle.AspNetCore.
In .NET Core 3, there's some issues as discussed here. The solution is to add the following to the project file, replacing the prior version.
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc2" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0-rc2" />

For the .Net core project, you need to install Four packages. Better to use Nuget package manager so it takes appropriate needed versions.
Microsoft.OpenApi
Swashbuckle.AspNetCore.Swagger
Swashbuckle.AspNetCore.SwaggerGen
Swashbuckle.AspNetCore.SwaggerUI

This happens because the implementation of AddSwaggerGen() extension method in ASP.NET Core requires you to provide Action<SwaggerGenOptions> argument which serves as setup action. For example:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
You can learn more on how to setup Swagger with ASP.NET Core app here.
UPDATE:
In previous versions they had the AddSwaggerGen() extension method accepting no arguments, but this call was accompanied with call ConfigureSwaggerDocument(Action<SwaggerGenOptions> setupAction). I guess they just got rid of ConfigureSwaggerDocument and added setup action to AddSwaggerGen() method. That being said it seems your tutorial shows how to setup obsolete version of the Swagger.

Late answer, but as a new update on this question, I just noticed in order to make AddSwaggerGen works fine in .NET Core 3, you need to use OpenApiInfo instead of Info. So your new AddSwaggerGen should be something like this:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "The API", Version = "v1" });
});
Also you need to add the following to your using directives:
using Microsoft.OpenApi.Models;
Read more here https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio

If you are experiencing this problem while trying to deploy a web app and adding the Swagger spec to API Management in Azure (from Visual Studio) -> check the local path for your repo - if it has a space in it, it will fail.
To fix - move your repo to a different location so the path has no space.
I was using version 6.1.4 of the Swashbuckle.AspNetCore package.

It was working for me by install Nuget package of "Swashbuckle.AspNetCore" in the current project.
https://github.com/domaindrivendev/Swashbuckle.AspNetCore

Related

Can't add Sentry to ASP.NET Core Web API project in .NET 6

I am trying to add Sentry to my ASP.NET Core Web API project using .NET 6. However, I am encountering an issue where I cannot find the AddSentry method in IServiceCollection, even though I have installed the Sentry.AspNetCore package.
I have followed the instructions on the Sentry documentation and added the SentryAspNetCore package to my project. I also added the following line to my Program.cs file:
builder.Services.AddSentry();
However, I get the following error when building my project:
'IServiceCollection' does not contain a definition for 'AddSentry' and the best extension method overload 'LoggingBuilderExtensions.AddSentry(ILoggingBuilder, string)' requires a receiver of type 'ILoggingBuilder'
It seems that AddSentry is not recognized as an extension method of IServiceCollection. I have searched for similar issues and found some suggestions to add the Sentry.Extensions.Logging package, but that did not help.
Can anyone help me figure out what I am doing wrong and how I can add Sentry to my ASP.NET Core 6 Web API project? Thank you in advance!
You need to install Sentry.Extensions.Logging nuget and add using Sentry.Extensions.Logging.Extensions.DependencyInjection; and then call:
builder.Logging.AddSentry(); // use Logging, not Services
Docs.

Microsoft OData in .NET CORE 5 - Adding OData to services throws up a missing using directive yet the package is there

I am developing in .net core 5.0. (There is a tutorial by Sam Xu on moving to dotnet core 5)
I have gone back to the absolute bare minimum with the most simple API project in Visual Studio.
I had this working in my project earlier in the year and it was running on .net core 5.0. See tutorial above.
In this project I have created a new project. Then I went to NuGet to get the package "Microsoft.AspNet.OData" version 7.4.1
I then added the following to the startup file.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors();
services.AddControllers();
services.AddOData(); //THIS ONE
}
I added "services.AddOData" and its throwing up the error,
Error CS1061 'IServiceCollection' does not contain a definition for 'AddOData' and no accessible extension method 'AddOData' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?) JobsLedger.API C:\Users/.../JobsLedger.API\Startup.cs 35 Active
I had already added the package required for this service. Now I had this working a couple of months ago.
Is there a new package that you need to add?
What am I doing wrong or is this a "breaking change" that I dont know about?
if you are using .net5.0 it required odata 8.0 preview.
In rc2, according to this article https://devblogs.microsoft.com/odata/attribute-routing-in-asp-net-core-odata-8-0-rc/, Sam Xu made a breaking change.
"AddOData is changed from extensions on ISerivceCollection to extension on IMvc(Core)Builder.
The migration is easy by calling AddControllers() first, then calling AddOData()."
services.AddControllers()
.AddOData(opt => opt.AddModel("odata", GetEdmModel()));
[UPDATE - 11/2021]
In odata 8.0 AddModel doesn't exist anymore, it was renamed with AddRouteComponents
services.AddControllers()
.AddOData(opt => opt.AddRouteComponents("odata", GetEdmModel()));
https://devblogs.microsoft.com/odata/api-versioning-extension-with-asp-net-core-odata-8/

what is the equivalent of "startup.cs"(.Net Core) in my .Net framework application?

Startup.cs has some methods which can be used to configure swagger to add file upload functionalities , now in which file in .NET Framework can i do the same functionalities?
As you said you want to configure Swagger in dot net framework so you need to install Swashbuckle just open package manager and type following commands
Install-Package Swashbuckle -Version 5.6.0
then look in your App_Start file you will find SwaggerConfig.cs where you can configure it
the minimum, you’ll need this line to enable Swagger and Swagger UI.
GlobalConfiguration.Configuration
.EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API"))
.EnableSwaggerUi();
Look here for long Explanation

EF Core 1.1 to WebApi Core - Add-Migration fails

I think I’ve got all my dependencies running 1.1 properly but when I try to follow the steps here https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db I get an error running the Add-Migration command.
PM> Add-Migration InitialState
An error occurred while calling method ‘ConfigureServices’ on startup class ‘Startup’.
Consider using IDbContextFactory to override the initialization of the
DbContext at design-time. Error: This method could not find a user
secret ID because the application’s entry assembly is not set. Try
using the “.AddUserSecrets(Assembly assembly)” method instead. No
parameterless constructor was found on ‘ApplicationDbContext’. Either
add a parameterless constructor to ‘ApplicationDbContext’ or add an
implementation of ‘IDbContextFactory’ in the same assembly as
‘ApplicationDbContext’.
relevant sections of my project.json:
…
“Microsoft.EntityFrameworkCore”: “1.1.0”,
“Microsoft.EntityFrameworkCore.SqlServer”: “1.1.0”,
“Microsoft.EntityFrameworkCore.Design”: {
“type “: “build”,
“version”: “1.1.0”
},
“Microsoft.EntityFrameworkCore.Tools”: “1.1.0-preview4-final”
},
“tools”: {
“Microsoft.EntityFrameworkCore.Tools.DotNet”: “1.1.0-preview4-final”
},
My ApplicationDbContext does have the constructor:
public ApplicationDbContext(DbContextOptions options) : base(options)
{ }
and my Startup.cs does have the:
services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”)));
What else can it be?
The issue is related to the builder.AddUserSecrets() call. To fix perform the following steps:
Adding the user secret to the assembly (instead of just project.json) by adding attribute [assembly: UserSecretsId("aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed")] to Startup.cs
In Startup.cs replace builder.AddUserSecrets() with builder.AddUserSecrets<Startup>();
Reference: InvalidOperationException: Could not find 'UserSecretsIdAttribute' on assembly
An alternate solution:
I ran into the same problem and landed here. But I am writing an app from scratch comparing it at every step with the DotNetCore WebApp with Individual auth. that gets generated via wizard in VS 2017 hoping to follow latest practices. So it was strange when everything was identical in my code and the generated code and I was getting this exception. The generated code did not have Michael Dennis's suggested code in startup.cs, which does not mean he is wrong, it just means there was now a different way. Upon diving down further I found out that UserSecretsId was declared in myprojetname.csproj like follows:
<PropertyGroup>
<UserSecretsId>aspnet-mywebproect-006a401f-2fdc-4aad-abb1-12c00000004a</UserSecretsId>
</PropertyGroup>
After adding the entry in my project.csproj file, the issue was resolved.
Your issue is not related to EF Core, it's about User Secrets
Check your Startup.cs constructor - it contains AddUserSecrets() call. You can remove it. Later, when you read about User Secrets, you can add it back with correct configuration (I guess you have website template from 1.0.0, while referencing library 1.1.0 - it contains this bug fix)

Can't find method app.UseStaticFiles()

I'm following this guide and in step 4, I'm asked to add three lines to the project.json file (which I did and then ran dotnet restore getting a lot of updated packages).
When I enter the three lines in the Configure method, I get red lines on all of them. The methods aren't recognized, no intellisense provided etc.
I also noticed that in the example in the guide, the method signature only takes one parameter of IApplicationBuilder, whereas the one I got generated (using the yo aspnet command) looks like this.
Configure(IApplicationBuilder, IHostingEnvironment, ILoggerFactory);
I'm not sure how to resolve it. My guess is that there's a new version of something in the process (Yo, Generators, Core etc.) but I'm not entirely sure.
I've also found this blog where the method signature resembles the one I'm getting. However, the author of it suggest the same syntax that doesn't work for me. I'm guessing it's a matter of referencing the wrong libraries. How do I approach the issue?
For Asp.Net core MVC you need to install Nuget package
install-package "Microsoft.AspNetCore.StaticFiles"
That guide is outdated. The updated .Net core does not use project.json anymore which is unfortunate. Instead it is now part of csproj file. And to add the Static file library you have to add it to the project using nuget packet manager. And when you rebuild you will see an entry in csproj file for that library. I think the project.json was a great idea which was inline with core opt-in methodology, since it would allow intellisense to kick in to help you select from available libraries. And since csproj file cant be directly edited in solution you lose that feature.
Judging from the screenshots in the linked tutorial, its about ASP.NET Core RC1 (back then called ASP.NET 5 r1-final). You can easily recognize this on the package and namespace names. Microsoft.AspNet.* is used until rc1.
Starting with RC2 the packages were renamed to Microsoft.AspNetCore.* to make it clearer its a new framework and not that much compatible with legacy ASP.NET.
The UseIISPlatformHandler() isn't there anymore, it's now UseIISIntegration() within the Main(...) method:
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
And the packages the package is Microsoft.AspNetCore.Server.IISIntegration": "1.0.0" and "Microsoft.AspNetCore.Server.Kestrel": "1.0.1". For static files it's: "Microsoft.AspNetCore.StaticFiles": "1.0.0".
For the Configure overload: Configure(IApplicationBuilder); is default one, but you can add any other type which is registered with the dependency injection system (in ConfigureServices method), as it's a convention system (the startup.cs).

Categories

Resources