I have a ASP.NET Core 5.0.1 project and planning to create authentication on swagger UI but I encounter some issues on the services controller. Which is the error code below. Regarding this I have seen an issue similar to me in this Link but my issue is not resolve even added the NewtonsoftJson. Any ideas on this kind of issue.
Error CS1061 'IServiceCollection' does not contain a definition for
'AddControllers' and no accessible extension method 'AddControllers'
accepting a first argument of type 'IServiceCollection' could be found
(are you missing a using directive or an assembly reference?
using Microsoft.Owin;
using Owin;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
[assembly: OwinStartup(typeof(ABSRestService.App_Start.Startup1))]
namespace ABSRestService.App_Start
{
public class Startup1
{
public Startup1(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigurationServices(IServiceCollection services)
{
services.AddControllers();
}
}
}
At first Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJsonand then
Try this, it should work.
services.AddControllers().AddNewtonsoftJson();
Related
I am trying to follow Microsoft's Ocelot API Gateway tutorial (https://learn.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot).
First I intialized a new empty ASP.NET Core web app:
dotnet new web
Then I installed the Ocelot dependencies (https://www.nuget.org/packages/Ocelot/):
dotnet add package Ocelot --version 17.0.0
Then I took the code from the tutorial:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using System.IO;
namespace MyApp
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
var builder = WebHost.CreateDefaultBuilder(args);
builder.ConfigureServices(s => s.AddSingleton(builder))
.ConfigureAppConfiguration(
ic => ic.AddJsonFile(Path.Combine("configuration",
"configuration.json")))
.UseStartup<Startup>();
var host = builder.Build();
return host;
}
}
}
But then it complains that the WebHost class, called in BuildWebHost method, "is inaccessible due to its protection level". According to Microsoft (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webhost), WebHost "provides convenience methods for creating instances of IWebHost and IWebHostBuilder with pre-configured defaults.", and looks like so:
public static class WebHost
...
Why does it complain that WebHost is inaccessible, when the class is in fact public? What am I missing here?
From the documentation, WebHost is in the namespace Microsoft.AspNetCore. But in your code, It hasn't the using to this namespace.
In Visual Studio, you can try Go to definition on WebHost to discover where the type come.
As sujested by #leiflundgren, as your code has the using Microsoft.AspNetCore.Hosting, then the compiler thinks you want use Microsoft.AspNetCore.Hosting.WebHost.
https://github.com/dotnet/aspnetcore/blob/main/src/Hosting/Hosting/src/Internal/WebHost.cs
namespace Microsoft.AspNetCore.Hosting;
internal sealed partial class WebHost : IWebHost, IAsyncDisposable
{
....
}
But this class has the scope internal, then it isn't exposed and can be used by your code. Hence the following error :
WebHost is inaccessible due to its protection level.
I am setting up Aws SQS in asp.net core 2.22 project. I am adding aws configuration lines in my Program.cs file. Here is my Program.cs file.
using Amazon.SQS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace analytics
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; set;}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options =>
{
options.AllowAnyOrigin();
});
});
// AWS Configuration
var awsoptions = Configuration.GetAWSOptions();
services.AddDefaultAWSOptions(awsoptions);
services.AddAWSService<IAmazonSQS>();
// Worker Service
// services.AddHostedService<Worker>();
}
// 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();
}
else
{
// 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.UseHttpsRedirection();
app.UseMvc();
app.UseCors(options =>
{
options.AllowAnyOrigin();
});
}
}
}
So i am receiving these errors on console
Startup.cs(40,52): error CS1061: 'IConfiguration' does not contain a definition for 'GetAWSOptions'
and no accessible extension method 'GetAWSOptions' accepting a first argument of type
'IConfiguration' could be found (are you missing a using directive or an assembly reference?)
[D:\OfficeProjects\beelinksanalytics\analytics.csproj]
Startup.cs(41,30): error CS1061: 'IServiceCollection' does not contain a definition for
'AddDefaultAWSOptions' and no accessible extension method 'AddDefaultAWSOptions' accepting a first
argument of type 'IServiceCollection' could be found (are you missing a using directive or an
assembly reference?) [D:\OfficeProjects\beelinksanalytics\analytics.csproj]
Startup.cs(42,30): error CS1061: 'IServiceCollection' does not contain a definition for
'AddAWSService' and no accessible extension method 'AddAWSService' accepting a first argument of
type 'IServiceCollection' could be found (are you missing a using directive or an assembly
reference?) [D:\OfficeProjects\beelinksanalytics\analytics.csproj]
Basically i want to implement Aws SQS service to listen queue messages and want to perform some actions based on those messages. So i am struggling to configure Aws Sdk and aws sqs in asp.net core 2.2 project
I didn't find any relevant documentation of how to configure aws sqs in asp.net core 2.2. Please tell me what's wrong with this?
just run this in your command line as mentioned #panagiotis-kanavos (select version that you want here)
dotnet add package AWSSDK.Extensions.NETCore.Setup --version 3.3.101
verify that the reference was added in your .csproj
this worked for me, I hope as well for you
I'm currently trying to create a Logger so I can inject it in Unit Tests. I'm following https://stackoverflow.com/a/43425633/1057052, and it used to work! I then moved the project and reestablished the dependencies, and now I'm getting
'ServiceCollection' does not contain a definition for 'AddLogging' and
no accessible extension method 'AddLogging' accepting a first argument
of type 'ServiceCollection' could be found (are you missing a using
directive or an assembly reference?)
There must be something silly I'm missing. Currently under ASP.NET Core 2.2, and I believe I have assigned the correct dependencies.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection?view=aspnetcore-2.2
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.loggingservicecollectionextensions.addlogging?view=aspnetcore-2.2
I've been reinstalling for the past hour our so! Can't nail what the problem is
Here's the code:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Planificacion.UnitTest.Config
{
public class LoggerTestConfig
{
private LoggerTestConfig()
{
}
// https://stackoverflow.com/a/43425633/1057052
public static ILogger<T> GetLoggerConfig<T>() where T : class
{
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
var factory = serviceProvider.GetService<ILoggerFactory>();
return factory.CreateLogger<T>();
}
}
}
The image highlights that the dependency injection dll is referenced, but desired LoggingServiceCollectionExtensions.AddLogging Method as shown in the links provided, indicates
Namespace: Microsoft.Extensions.DependencyInjection
Assembly: Microsoft.Extensions.Logging.dll <----NOTE THIS
Which is not referenced as shown in the image.
Add a reference to the Microsoft.Extensions.Logging.dll assembly stated above.
I'm new to ASP.NET Web API and want to make HttpResponseMessage instance from a utility class I made. Then I made very simple class.
But following compile error occurred.
CS0246: The type or namespace name 'HttpResponseMessage' could not be
found (are you missing a using directive or an assembly reference?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
namespace myapplication.App_Code.Utils
{
public class HttpUtility
{
// compile error here
public HttpResponseMessage GetHttpResponseMessage ()
{
return new HttpResponseMessage();
}
}
}
HttpResponseMessage is available from Controller Class which was made automatically by ASP.NET but not my Utility class.
What am I missing?
I have noticed that you placed your class in App_Code folder in your project. This folder has a special purpose in ASP.NET world and should be used for shared classes and business objects that you want to compile as part of your application. So either move your class into another folder, or change its Build Action in properties section to Compile.
I have a C# solution composed of three projects in Visual Sudio 2010. One is X.Domain (class library) the second, X.UnitTest and the third X.WebUI (MVC3). I was having problems with the using statement to reference the X.Domain namespace from withing the X.WebUI namespace. I thought it was a client profiling issue and verifired that all of the projects where using ".Net Framework 4" as the target framework. I checked to make sure the project dependencies for X.WebUI included the namesapce X.Domain. The exact errors I'm getting are:
The type or namespace name 'Domain' does not exist in the namespace'X' (are you missing an assembly reference). The error for the interface I'm trying to use from within X.Domain.Abstract: The type or namespace name 'IPersonRepository' could not be found (are you missing a using directive or an assembly reference)
In the X.Domain namespace/project, there are public methods, so I'm not sure why it's not exposed. I looked into these links here on stackoverflow, but they did not resolve the issue. Visual Studio 2010 suddenly can't see namespace?,
The type or namespace name could not be found ,
The type or namespace 'MyNamespace' does not exist etc
It's worth mentioning that someone posted that it could have something to do with a missed configured global.asax file, here
Type or namespace name does not exist
in that link, but I'm not sure about it. Could be the case, so I am posting my Global.asax file as well. I noticed the problem when I'm trying to create my 'PersonController' with ninject MVC3, I used Remo.gloo's blog to help me create the Global.asax file as posted here http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/ and am following along with some additional code on p.164 of the the Pro ASP.NET MVC3 Framework book to create the controller.
PersonController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KLTMCInsight.Domain.Abstract;
namespace KLTMCInsight.WebUI.Controllers
{
public class PersonController : Controller
{
private readonly IPersonRepository repository;
public PersonController(IPersonRepository personRepository)
{
repository = personRepository;
}
}
}
Global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Reflection;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;
namespace KLTMCInsight.WebUI
{
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
If I missed something you need, I'll be more than glad to post it up. Again, Thank you for your help- Very appreciated.
Here is the solution:
I had used the 'Project Dependencies' box listed under the 'Project' file menu to select the dependencies of the X.WebUI project. Even though on in it I had checked the box for the X.WebUI project to depend on the X.Domain project... the reference was never created by VS2010. To solve the issue it was a simple fix by manually right-clicking the References folder under X.WebUI, and adding the reference to X.Domain through that window. Reference was added problem solved. Not sure why the reference was not made from the 'Project Dependencies' box in the first place, but if anyone comes across this same problem- this should remind you to check if the reference was actually made.