Add a Startup.cs file in MVC5 project without authentication - c#

How can I bind the startup.cs file adding manually to the project?
I created it from Add > New Item > OWIN Startup class but is ignored by the app.
The Startup class
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApplication1.Startup))]
namespace WebTest
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
}
}
}
Thanks
Update
I can do it thanks to this
OwinStartup not firing

[assembly: OwinStartup(typeof(**WebApplication1**.Startup))]
In the OwinStartup attribute you specify a class WebApplication1.Startup but the class shown says WebTest.Startup

Related

'IServiceCollection' does not contain a definition for 'AddControllers' even added newtonjson

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();

'WebHost' is inaccessible due to its protection level

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.

asp.net core: IApplicationLifetime.ApplicationStopping isn't triggered

I saw a few articles about IApplicationLifetime and the way I can trigger execution when application starts and stops but I probably miss something because it is just not triggered.
Here is my workaround:
I opened a project template Container Application for kubernetes, asp.net core 2.2
Program.cs looks as it was created:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Kubernetes1
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Startup.cs looks as following:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Kubernetes1
{
public class Startup
{
// 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)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//var appLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
appLifetime.ApplicationStopping.Register(() => Console.WriteLine("ApplicationStopping called"));
appLifetime.ApplicationStopped.Register(() => Console.WriteLine("ApplicationStopped called"));
app.Run(async (context) =>
{
Console.WriteLine("AAA");
});
}
}
}
All I wanted to do here is running the app in cmd, then stop it and see 2 lines printed in console:
ApplicationStopping called
ApplicationStopped called
I didn't manage to make it happen.
Any ideas?
in a different cmd window I type: Get-Process -Name *dotnet* | Stop-Process
Stop-Process will kill the process, skipping any graceful shutdown behavior an application might have.
When the IApplicationLifetime talks about the application stopping, then it refers to the application being gracefully shut down. There are a few ways to trigger this, depending on how the application is starting:
When the application is running in the console: CTRL + C. For example when running through dotnet run or running the compiled executable directly.
When the application is running in IIS: Stopping the website or the application pool.
When the application is running as a Windows Service: Stopping the service.

The type Merge.CustomDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator

I am trying to create generic controller for that i am following this approach(http://jonahacquah.blogspot.in/2011/12/writing-aspnet-mvc-3-generic.html) after completion of coding while running the application i am getting these error(The type Merge.CustomDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator), in the Global.asax file.
This is my Global.asax.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace Merge
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(typeof(controllerFactory));
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
System.Web.Mvc.DependencyResolver.SetResolver(new CustomDependencyResolver()); // I am getting the error in this line
}
}
}
can any one please help me to solve this problem, Thank you

Microsoft Azure AD authentication giving 'System.Net.Http.HttpRequestException'

I am facing a strange imtermittent issue with Azure AD authentication.
We are using CORS enabled web api in our project (origins are specified in web.config which are fetched by custom attribute, and this attribute is used for controllers).
Athorization part is done using adal.js
code is as follows:
startup.cs
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
[assembly: OwinStartup(typeof(test.testapi.WebApi.Startup))]
namespace Test.testapi.WebApi
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
Startup.auth.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Claims;
using Microsoft.Owin.Security.ActiveDirectory;
using System.Configuration;
using Owin;
using System.Net;
namespace test.testapi.WebApi
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
//Following line is not required if you are using HTTPS calls to APIs
//ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = ConfigurationManager.AppSettings["ida:Audience"],
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
});
}
}
}
When the control goes to startup.auth.cs it gives System.Net.Http.HttpRequestException
Error
Now thing is while i was working on my local dev environment i never got this issue(always authenticated fine ) but QA was facing this issue on QA server, so we started hosting web api from my machine, After which i also started getting this issue and that too quite frequently now.
what is this issue if anyone has faced this same issue.

Categories