I am trying to integrate swagger into a ASP NET Core 3.0 project and it throws exception right in the ConfigureServices method:
I am using Swashbuckle.AspNetCore 4.0.1.
I have also checked this issue and also this
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Version = "v1",
Title = " API",
Description="API for the Server",
});
});
}
Exception
System.AggregateException
HResult=0x80131500
Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.Swagger.ISwaggerProvider Lifetime: Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator': Failed to compare two elements in the array.) (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory Lifetime: Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryFactory': Failed to compare two elements in the array.)
Source=Microsoft.Extensions.DependencyInjection
StackTrace:
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at SXS.Server.Program.Main(String[] args) in C:\Work\SXS\SXS\Core\Server\SXS.Server\Program.cs:line 32
Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.Swagger.ISwaggerProvider Lifetime: Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator': Failed to compare two elements in the array.
Inner Exception 2:
InvalidOperationException: Failed to compare two elements in the array.
Inner Exception 3:
TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
P.S I have followed this guide and the only difference is that while he uses a OpenApiInfo object i do not have that overload available and thus am using a Info.
I experienced this issue, using .Net Core 3.1.2 and Swagger 5.4.1.
Turns out I forgot to add services.AddControllers(); to my Startup::ConfigureServices method.
I was only adding Razor Pages.
I just went through Get started with Swashbuckle and ASP.NET Core at learn.microsoft.com and had no problem.
The docs explain you need to use the latest preview version of Swashbuckle.AspNetCore, 5.0.0-rc4
This is usually due to usage of wrong swagger package and as a result the Info api is using Swashbuckle.AspNetCore.Swagger.Info which caused the problem.
If you use the latest Swashbuckle.AspNetCore, 5.0.0-rc4m package then it will take OpenApiInfo from new Microsoft.OpenApi.Models and then it will work.
Happy Coding!
I tried this and it worked fine:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "My API",
Description = "My API description for blah blah"
});
});
Btw I'm using .Net Core 2.1
Related
I am creating an Web Api using .Net Core 5. I want to implement error handling and return the response with the error. I found a article from Microsoft which suggested the following code. When I am implementing that code "HttpResponseException" is not found and I get a suggestion to install the nuget package for Microsoft.Aspnet.WebApi.Core. Once install it conflicting with the existing nuget package. I got this message "Microsoft.AspNet.WebApi.Core 5.2.8 was restored using .netFramework, Version=4.6.1..." As I said, I am trying to handling error as per best practices and my finding was to use Microsoft documentation in which it mentioned to use HttpResponseException (applicable scenario). If HttpResponseException is obsolete for .Net 5 what other option we have? Basically in the response when error occured, I want to send the customize ReasonPhrase.
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found"
};
throw new HttpResponseException(resp);
}
return item;
}
using BreezeJs for .net core 3.1
Issue with fixupKeys when saving new entity
throws "Unable to locate the following fully qualified EntityType name: "
Examining this: the _entityGroupMap entries use another fully qualified format than the keymappings object
e.g.
HoseColor:#Urflex.Webshop.Model (_entityGroupMap) <<==>> Urflex.Webshop.Model.HoseColor (keymappings)
How to resolve this?
problem solved. Overlooked some configuration in startup.cs file of the web api project.
As the breeze documentation states:
var mvcBuilder = services.AddMvc();
services.AddControllers().AddNewtonsoftJson(opt =>
{
// Set Breeze defaults for entity serialization
var ss = JsonSerializationFns.UpdateWithDefaults(opt.SerializerSettings);
if (ss.ContractResolver is DefaultContractResolver resolver)
{
resolver.NamingStrategy = null; // remove json camelCasing; names are converted on the client.
}
ss.Formatting = Newtonsoft.Json.Formatting.Indented; // format JSON for debugging
});
// Add Breeze exception filter to send errors back to the client
mvcBuilder.AddMvcOptions(o => { o.Filters.Add(new GlobalExceptionFilter()); });
I am trying to use Swagger in an AspNet Core 2 Web API. I have one sample that works based on:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
However, when I try to use the same approach in another service I get compile error:
2>Startup.cs(41,17,41,27): error CS0121:
The call is ambiguous between the following methods or properties:
'Microsoft.AspNetCore.Builder.SwaggerBuilderExtensions.UseSwagger(Microsoft.AspNetCore.Builder.IApplicationBuilder,
System.Action)'
and
'Microsoft.AspNetCore.Builder.SwaggerBuilderExtensions.UseSwagger(Microsoft.AspNetCore.Builder.IApplicationBuilder,
string, System.Action)'
2>Done building project "SocialNetwork.Api.csproj" -- FAILED.
The target call is in Startup.cs in the Configure method.
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(); // Ambiguous
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SocialNetwork API V1");
});
app.UseMvc();
}
Does anyone have insight on this? Any help would be greatly appreciated.
Thank you.
I uninstalled Swagger and just installed the SwashBuckle.AspNetCore because it already implements the Swagger object inside. that is why it is calling ambigious.
Could it be that you have references to multiple Swagger-libraries? In my case I had accidentally added a reference to other swagger-related Nuget packages, and that caused the same error as you described.
Just uninstall the Swagger nugget package and you should be fine
I am facing weird issue.
I am reading and creating OpenID Connect server with ASOS this article ASOS - AspNet.Security.OpenIdConnect.Server.
I simply created new sample solution and added new subclass AuthorizationProvider class of OpenIdConnectServerProvider and override the virtual method i.e. ExtractAuthorizationRequest
AuthorizationProvider.cs
public class AuthorizationProvider : OpenIdConnectServerProvider
{
public override Task ExtractAuthorizationRequest(ExtractAuthorizationRequestContext context)
{
// If a request_id parameter can be found in the authorization request,
// restore the complete authorization request stored in the user session.
if (!string.IsNullOrEmpty(context.Request.RequestId))
{
var payload = context.HttpContext.Session.Get(context.Request.RequestId);
if (payload == null)
{
context.Reject(
error: OpenIdConnectConstants.Errors.InvalidRequest,
description: "Invalid request: timeout expired.");
return Task.FromResult(0);
}
// Restore the authorization request parameters from the serialized payload.
using (var reader = new BsonReader(new MemoryStream(payload)))
{
foreach (var parameter in JObject.Load(reader))
{
// Avoid overriding the current request parameters.
if (context.Request.HasParameter(parameter.Key))
{
continue;
}
context.Request.SetParameter(parameter.Key, parameter.Value);
}
}
}
return Task.FromResult(0);
}
}
Issue:
As soon as i add Microsoft.AspNetCore.Identity (2.0.0) NuGet package to my project, context.Reject start giving the following error
"Reference to type 'BaseControlContext" claim it is defined in
Microsoft.AspNetCore.Authentication, but it could not be found.
But as soon as I remove Microsoft.AspNetCore.Identity NuGet dependency, the error goes away and all looks fine.
Note:
I am using VS 2017.
I am using dotnetcore 2.0 SDK.
I created solution using .Net Core 2.0.
Massive changes have been introduced in ASP.NET Core 2.0's authentication stack. The changes are so important that all the authentication middleware written for ASP.NET Core 1.x are not compatible (which includes all the aspnet-contrib projects).
You can read https://github.com/aspnet/Announcements/issues/262 for more information.
The good news is that we have an ASP.NET Core 2.0 RTM-compatible version of ASOS. You can find the 2.0.0-preview1-* bits on the aspnet-contrib MyGet feed (https://www.myget.org/F/aspnet-contrib/api/v3/index.json).
we have been using the ASANA API about 4 month, but today we started get an error trying to create task in Asana:
5:15:48,208 ERROR [stderr] (pool-13-thread-1) Exception in thread "pool-13-thread-1" com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "num_hearts" (Class net.joelinn.asana.tasks.Task), not marked as ignorable
05:15:48,210 ERROR [stderr] (pool-13-thread-1) at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#6eae04be; line: 1, column: 296] (through reference chain: net.joelinn.asana.tasks.Task["num_hearts"])
the error happens on client.createTask() call, see the code below:
protected void createProjectTasks(Project template, AsanaDetails asanaDetails, Long createdProjectId) {
try {
String asanaWorkspaceName = asanaDetails.getWorkspaceName();
Asana asana = new Asana(asanaDetails.getApiKey());
Tasks tasks = asana.projects().getTasks(template.id);
Workspace workspace = getWorkspace(asana, asanaWorkspaceName);
if (workspace == null) {
throw new AsanaException("Asana workspace with name " + asanaWorkspaceName + " is not found");
}
if (tasks == null) {
return;
}
Collections.reverse(tasks);
TasksClient client = asana.tasks();
for (Task task : tasks) {
TaskRequestBuilder taskRequestBuilder = new TaskRequestBuilder();
if (StringUtils.isNotBlank(task.name)) {
taskRequestBuilder.name(task.name);
taskRequestBuilder.completed(false);
taskRequestBuilder.addProject(createdProjectId);
taskRequestBuilder.workspace(workspace.id);
client.createTask(taskRequestBuilder);
}
}
} catch (ApiException e) {
throw new AsanaException(e.getMessage());
}
}
I checked the Task class, the are no field there annotated with "num_hearts", so, I'm a bit confused what got broken here, we haven't made any code changes for about a month...
and here is the api version:
<dependency>
<groupId>net.joelinn</groupId>
<artifactId>asana</artifactId>
<version>0.5.4</version>
</dependency>
Any thoughts?
Thanks in advance
We're happy to have released support in the API for hearts in both tasks and stories. These include the new fields, "hearted", "hearts", and "num_hearts". You can read more about this in our documentation.
Unfortunately, your client threw an error because it reached a new field (num_hearts) which it did not recognize. Since the client appears to be open source, you might want to send them a pull request to add support for the new hearts attributes. Alternatively, it may be worth to generalize the client so it does not throw an error when we add new fields in the future. In order to keep the API up-to-date with product developments, we will from time to time add fields and endpoints. You can rely on existing fields not going away, but it's bad to rely on no new fields being added.