I am trying to add the OWIN startup class in a new .Net core class library project. I have installed the package Microsoft.AspNetCore.Owin package. But I still don't see the option to create OWIN Startup class in Add New Items wizard. It used to be there in .Net class library earlier. Is it different in .Net Core class library?
I basically want to create a separate project for my SingalR hub and use it from wherever I want by just referencing it.
This has to do with the tooling of Visual Studio. When you are working on a web project Visual Studio recognizes this and presents web options in the Add New Items Wizard. Since you are working in a class library project Visual Studio does not think you need web based options and thus does not present it. Luckily, the startup class you want is a plain class with some conventions. You should be able to add a class called startup to your class library project and give it the following definition to get what you want:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyClassLibrary
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
}
}
}
Once I've created a ChatHub which derives from Microsoft.AspNetCore.SignalR.Hub<IChatClient>.
All components have been located in separate .net standard library.
IChatClient looks like (it's used for type safety):
public interface IChatClient
{
Task ReceiveChatMessage(string user, string message, DateTime sentAt, bool isMarkedAsImportant);
Task ReceiveChatActivity(string user, Activity activity, DateTime sentAt);
}
Finally I used that ChatHub in an ASP.net core project, where the hub is configured in Startup like this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseCors(builder =>
{
builder.WithOrigins("https://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
IdentityModelEventSource.ShowPII = true;
}
else
{
app.UseGlobalExceptionHandler();
app.UseHttpsRedirection();
app.NwebSecApiSetup();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/api/chat");
endpoints.MapHub<EventHub>("/api/events");
});
}
Additionally, I've configured something more for SignalR in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers().AddControllersAsServices();
services.AddHttpContextAccessor();
services.AddConnections();
services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
})
.AddNewtonsoftJsonProtocol();
...
}
I suppose you can easily use such Hubs in other projects as well.
Related
I have an .net5 project and in .csproj file I have this:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
I added Microsoft.EntityFrameworkCore package to my prject.furturemore I created Dbcontext file like below:
using Domian;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Mc2.CrudTest.Presentation.Front.Infrastructure
{
public class DataContext : DbContext
{
protected readonly IConfiguration Configuration;
public DataContext(IConfiguration configuration)
{
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// connect to sql server with connection string from app settings
options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"));
}
public DbSet<Customer> Customers { get; set; }
}
}
since there wasn't any startup.cs file in my project ,I created one this way:
the namespaces of IApplicationBuilder and IWebHostEnvironment coudn't find.
I dont know whether I can use startup.cs file like.net core.3.1 or I shouldn't use startup.cs file in .net5 anymore.
And my program.cs file was formed this way:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Mc2.CrudTest.Presentation.Front
{
public class Program
{
public static async Task Main(string[] args)
{
WebAssemblyHostBuilder builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
builder.Services.AddDbContext(options => options
}
}
}
In addtion my project is BlazorWebAssembly
First of all, don't use .NET 5. It reached End-of-Life on May 2022. That's almost a year ago. EOL means no support at all, for anything, from either Microsoft or NuGet authors. Not even security patches.
It was known from the start this would be a single-year or "Standard-Term" Support version (STS), supported only for 18 months. The Long-Term-Support version is .NET 6, supported until November 2024. LTS versions are supported for 3 years since release.
Second, you don't need Startup.cs in .NET 6 (or .NET 5). The methods found in Startup.cs were merged into Program.cs. You can write :
builder.Services.AddDbContext(options=>options
.UseSqlServer(builder.Configuration.GetConnectionString("SqlServerConnection")));
This is shown in all ASP.NET Core and EF Core tutorials, eg this Web API tutorial. In this tutorial, Program.cs contains :
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Notice that even Program.Main is missing. That's the entire file. This is possible through a few new C# features: top-level statements and implied usings.
If you don't like this style you can use --use-program-main to generate a Program.cs and Main method
First off, of course you should update to .NET6 or .NET7 if you can[1]. But if that's not practical for whatever reason, then of course you can use startup.cs. In fact I prefer to as well, out of habit (you can use it in .NET6 too; not sure about 7 but I assume so).
You can define startup.cs more or less the way you do, but you do need the right using's:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
Less obviously, in your program.cs you need
using Microsoft.AspNetCore;
...
public static async Task Main(string[] args)
{
...
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
...
}
Edit - After discussing with Amir in comments below it seems the scope of this problem is pretty different from what was originally asked. I suggest you spend some time in an example Blazor solution with a separate hosting project from the webassembly SPA project. Things will make a lot more sense after that.
[1] Microsoft IMO has done the world a disservice with its post-Framework policy of introducing breaking changes into each ASP.NET version so liberally. It's not always just a matter of retargeting. And that's especially true of Blazor which is still so immature. Certainly if security is a concern for this application you should be doing everything you can to upgrade, but in the real world isn't always that simple.
you should add blazerServerApp project which consist of program.cs and startup.cs which you looking for as shown below.
I was using this tutorial: Create a web API with ASP.NET Core but I get an error in Startup.cs after installing Microsoft.EntityFrameworkCore.SqlServer from Nuget.
The error message is:
Error CS1061 'DbContextOptionsBuilder' does not contain a definition for 'UseInMemoryDatabase' and no accessible extension method 'UseInMemoryDatabase' accepting a first argument of type 'DbContextOptionsBuilder' could be found (are you missing a using directive or an assembly reference?)
This instruction refers to this point in the project "Register the database context".
Here is the code for startup.cs:
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
namespace TodoApi
{
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.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddControllers();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I looked online but couldn't find any fix for this problem, I have to say I installed Microsoft.EntityFrameworkCore.SqlServer version 5.0, and in the tutorial is version 3.0 but I don't think this is the issue.
The error I get occurs here:
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
The article you used explains that you need to add the Microsoft.EntityFrameworkCore.InMemory package in the section Add a Database Context, in the Add NuGet packages box :
Use the preceding instructions to add the Microsoft.EntityFrameworkCore.InMemory NuGet package
This package adds the provider and the UseInMemoryDatabase extension method
Try adding the package: Microsoft.EntityFrameworkCore.InMemory
I am trying to create an Angular 8 project with asp.net Core 2.1.
Whenever I try to add migration using command
cmd command: dotnet ef migrations add init --project ../Lgn.DAL
The terminal throws error :
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
Startup.cs
``
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.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// 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
{
app.UseHsts();
}
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200");
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
app.UseHttpsRedirection();
app.UseMvc();
}
}``
Take a look at this solution to someone with a similar issue. Is your dependency injection setup all good? (number 2 on that list)
Here are the things to consider:
You get that error because to generate migrations you need either:
A DbContext with a default constructor (that is, a parameterless
constructor)
Being able to get the DbContext from ApplicationServices
(that is, Dependency Injection)
A design time factory that returns a
properly configured DbContext.
I have a small problem with my UWP app. First, the UWP app has the following capabilities:
Enterprise Authentication
Shared user certificates
Private Networks
User Account Information
Now I want to connect to a SignalR-Hub in an ASP.NET Core 2.1 Web API. The hub looks like this:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Test.Namespace
{
[Authorize]
public class SyncHub : Hub
{
public void SendUpdate()
{
Clients.All.SendAsync("Update");
}
}
}
And this is my Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Test.Namespace
{
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.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSignalR();
services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
}
// 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
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseSignalR(routes =>
{
routes.MapHub<SyncHub>("/syncHub");
});
app.UseMvc();
}
}
}
The whole API runs on an IIS with Windows Authentication configured. The Active Directory runs on the same machine.
And this is how my UWP app calls the Service:
HubConnection connection = new HubConnectionBuilder().WithUrl("http://Server:81/syncHub", options => {
options.UseDefaultCredentials = true;
}).Build();
await connection.StartAsync();
This call always throws a 401.
What am I doing wrong? I work on this Problem for more than a week now and I can't figure out why it is not working.
Thanks to all who will help me :)
Edit: So I tried a few thinks today and found out, that this is not a problem of SignalR itself.I created a ASP.NET Core console app with the exact same call and everything works fine. It also works when I hardcode the credentials in the UWP app. It only doesn't work when I use "UseDefaultCredentials" in UWP. I am completly clueless. I have rechecked the capabilities but this doesn't help either.
It seems app.UseHttpsRedirection(); fail to redirect the client credentials.
Try to make a test with https url.
var hubConnectionBuilder = new HubConnectionBuilder();
var hubConnection = hubConnectionBuilder.WithUrl("https://localhost:44381/timeHub",options => {
options.UseDefaultCredentials = true;
}).Build();
await hubConnection.StartAsync();
Finally!
The answer was realy hard to find, but now it is working!
According to this site: https://support.microsoft.com/en-us/help/303650/intranet-site-is-identified-as-an-internet-site-when-you-use-an-fqdn-o
the app identifies the call as a call to the internet and therefore does not allow sending the default credentials. I must add this page manually to the local Intranet sites with the Internet Explorer and than it worked like a charm.
Thank to all who helped me with this :)
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