the name configureauth does not exist - c#

i'm trying this tutorial
http://httpjunkie.com/2013/311/adding-mvc-5-identity-to-an-existing-project/
but is shows me an error
Error 5 The name 'ConfigureAuth' does not exist in the current context
this is my startup.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(TicketSystem.Startup))]
namespace TicketSystem
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
this is Startup.Auth.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
namespace TicketSystem.App_Start
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication();
}
}
}

You have different namespaces in both files: namespace TicketSystem.App_Start and namespace TicketSystem. Make sure they are the same. Or alternatively add using statement: using TicketSystem.App_Start in your startup.cs class.
If you check the example you'll see that both files are using the same namespace (namespace MVC5FullApp)

Related

Getting an error message "IAppBuilder could not be found"

I am doing user authentication using owin middleware. But for IppBuilder it is giving error "IAppBuilder could not found. Are you missing Reference?" I have already installed nuggets packages related to owin as shown while searching on google.
Any help would be appreciated. Here is my code:
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using OpenConfigure.Core;
[assembly: OwinStartup(typeof(CURDApis.API.Startup))]
namespace CURDApis.API
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}
}

Is it possible to connect asp.net core 2.1 web api with existing database in sql server?

I see an official video of visual studio show how to do this. But in the end, the instructor can't make it work, he must alter UseSqlServer() with UseInMemoryDatabase() in Startup.cs.
Here is my code, i follow his instruction.
Firstly, create a file with classes that one contain Dbcontext, others map with tables in database. In my case, database just have one table: Students. This is class contain Dbcontext:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HoangHoaTham.WebAPI.Entities
{
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options) : base(options)
{
}
public DbSet<Students> Students;
}
}
My Startup.cs, i add UseSqlServer here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HoangHoaTham.WebAPI.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HoangHoaTham
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(options
=> options.UseSqlServer(Configuration.GetConnectionString("HoangHoaTham")));
services.AddMvc();
}
//You don't need to reed the code below
// 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();
}
app.UseMvc();
}
}
}
Finally, I add ConnectionString into appsetting.json:
{
"ConnectionString": {
"HoangHoaTham": "Server=PC-PC\\SQLEXPRESS;Database=HoangHoaThamHighSchool;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Anh it doesn't work. The error :
enter image description here
Here is his video: https://www.youtube.com/watch?v=aIkpVzqLuhA
Skip to 50:47 to see how he did that.
Thank you so much.
The error is telling you that the result of Configuration.GetConnectionString("HoangHoaTham") is null. Therefore, there's some issue with your configuration, and it turns out there is: the connection string section in appsettings.json is supposed to be ConnectionStrings (plural). You've got ConnectionString (singular) instead.
The error is for the ConnectionString you used in appsetting.json just try this code in your appsetting.json1 and tweak the connectionstring` as per your requirements this would work.
ASP.NET Core Web API
{
"ApplicationInsights":{
"InstrumentationKey":""
},
"ConnectionStrings":{
"DefaultConnection":"Server=srvrName;Database=Test;User Id=User;Password=pass"
},
"Logging":{
"LogLevel":{
"Default":"Warning"
}
},
"AllowedHosts":"*"
}

In which module is the HttpContext.Session defined

I am in MVC Core application. I added System.Web to my using clause but still I cannot access httpcontext.Session. The intellisense does not give me any option for httpcontext. Thanks for your answer.
Edit:
I have found this answer: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/
But when I add the nuget package: Microsoft.AspNetCore.Session into my project the solution won't even load anymore. So I had to remove it
Edit: Now I have added the most recent version of the package from nuget console. But I still do not have HttpContext option in the intellisense so I cannot access the session. Please help..
In System.Web I have only the following object: HttpUtility and nothing more,
is there anyone that can help? Without Sessions I cannot write any applications. Should I reinstall Visual Studio?
Notice**: In my webforms application I have the object Session in system.web
As required I post my Startup.cs and the file in which I am trying to call the object Session:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Localization;
using WebCoreFly.Models;
namespace WebCoreFly
{
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();
services.AddDbContext<FlyDBContext>(options =>
options.UseSqlServer(Configuration["Data:WebCoreFly:ConnectionString"]));
services.AddSingleton<FlyRepository>();
}
// 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.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
the class in whic I am trying to call session:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace WebCoreFly.Models.ViewModels
{
public class UserRepository1
{
public UserRepository1()
{
System.Web.HttpContext //does not recognize it
}
}
}

Add a claim for another user in C#: Failing User import

I am trying to add a claim to a user via a web form based on some other SO questions here and here, but I cant resolve User when getting the Claims Identity. I tried changing it to ApplicationUser but that didnt have the Identity property. How do I fix this?
In my User Model (Called ApplicationUser.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
namespace sideboob.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
private readonly UserManager<ApplicationUser> _userManager;
public async void AddAsyncClaim(string id,string claimname,string claimvalue)
{
ApplicationUser user = await _userManager.FindByIdAsync(id);
var Identity = new ClaimsIdentity(User.Identity); //FAILS HERE
// Remove existing claim and replace with a new value
await _userManager.RemoveClaimAsync(user, Identity.FindFirst("AccountNo"));
await _userManager.AddClaimAsync(user, new Claim(claimname, claimvalue));
}
}
}
Try this:
using Microsoft.AspNetCore.Mvc;
I think it might be just an Import.

ASP.NET Core using Impersonation cannot access User Identity

I am building an ASP.NET Core API (1.1) in Visual Studio Code using Windows Impersonation for authentication. (The API allows researchers to create Samples.) I am using this impersonation middleware to handle authentication, which passes on the user identity nicely when connecting to the underlying SQL Server database.
However, for some write actions, I would like to add the name of the user who created the object as a value to the database (i.e. the name of the researcher creating the sample). I can't seem to make it work. I based my solution on the responses to these questions: How to get the current logged in user Id ASP.NET Core and ASP.NET Core Identity does not inject UserManager<ApplicationUser> and this tutorial, even though they seem to be aimed at storing the user identities in separate tables in the SQL server database, which is not my intent. I only need the username of the user sending the request.
I get the following error message on the line var user = await GetCurrentUserAsync(); in my controller.
The 'await' operator can only be used within an async method.
Consider marking this method with the 'async' modifier
and changing its return type to 'Task<IActionResult>'
My question is twofold:
How can I fix this error?
Is there an easier/better way to get the User Identity in my situation.
My Controller file
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using MyAPI.Model;
using MyAPI.Services;
namespace MyAPI.Controllers
{
[Route("api/[controller]")]
public class SamplesController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
[HttpPost]
public IActionResult Post([FromBody] Sample sample)
{
var user = await GetCurrentUserAsync();
var userId = user?.Id;
// I abstracted the underlying logic of creating a sample in the database
//because it is quite complex and doesn't seem relevant to this problem
CreateSample(sample, userId);
}
}
}
Startup.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using MyAPI.Model;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Impersonate.AspNetCore.Windows;
namespace MyAPI
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseWindowsImpersonation(options => { options.Enabled = true; });
app.UseMvc();
}
}
}
MyAPI.Model.ApplicationDbContext file
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace TrinityAPI.Model
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
{
Database.EnsureCreated();
}
}
}
MyAPI.Model.ApplicationUser file
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace TrinityAPI.Model
{
public class ApplicationUser : IdentityUser
{
}
}
With Windows authentication enabled and inside the code for a controller action, you can find out information about the current user by going to the User object on the HttpContext property. For example, the following action should show domain\username for the current user.
public IActionResult Index()
{
return Content(HttpContext.User.Identity.Name);
}
When using Windows authentication, your are correct in thinking that you don't want to use ASP.NET Identity. You can remove the ApplicationDbContext class as well as the AddIdentity call in your Startup class.

Categories

Resources