Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

How does cookie authentication in identity framework work?

$
0
0

When a user signs in, I'm able to create a new cookie cookie and send it back to their browser. However, no user is being set when I call SignInAsync. 

Here is where I'm setting the cookie.

 var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, authRequest.UserName),
                new Claim(ClaimTypes.Name, authRequest.UserName),
                new Claim(ClaimTypes.Email, "TestClaim@Test.com")
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1),
                IsPersistent = true,
                IssuedUtc = DateTimeOffset.UtcNow
            };

            await this._httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties).ConfigureAwait(true);

Here is my startup.cs file options:

  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.Cookie.Name = "MyCookie.Identity";

                    options.Cookie.Expiration = TimeSpan.FromDays(1);
                    
                });

I have no idea what is happening once SignInAsync is called, but it's setting the options in my startup.cs. When I try to relogin with the user and they send the cookie, the httpcontext.User of the request is still anonymous user.  Any help would be appreciated!


Make this code generic

$
0
0

Hi (again)


I am trying to get used for generics. Playing with ASPNet Core 3.0

In my scenario I have configured a startup filter for configuration validation. Specifically I want to validate IdentitySettings that are holding in appsettings. Well.
I expose the working code and I would like to know a solution to make it generic and reusable.

In configure method I am doing 

  builder.ConfigureServices((services) =>
            {
                services.Configure<IdentityStartupSettings>(Configuration, binder => new IdentityStartupSettings());

                services.AddSingleton(resolver =>
                {
                    var identityStartupConfig = resolver.GetRequiredService<IOptions<IdentityStartupSettings>>().Value;
                    return identityStartupConfig;
                });
                services.AddConfigValidation<IdentityStartupSettings>();

IdentityStartupSettings is my POCO class that has settings definition. I am using DataAnnotations.

AddConfigValidation is an extension method I did to perform validation service injection

 public static IServiceCollection AddConfigValidation<T>(this IServiceCollection services) 
            where T : IValidateConfig
        {
            services.AddTransient<IStartupFilter, ValidateConfigFilter>();

            services.AddSingleton<IValidateConfig>(provider => provider.GetRequiredService<T>());

            return services;
        }

Now the questions:
First is simple. When I am doing services.Configure<IdentityStartupSettings>(Configuration, binder => new IdentityStartupSettings()); I am not sure if binder => new IdentityStartupSettings() means that it with bind to an instance of IdentityStartupSettings. I would like to know a scenario where it parameter is more interesting that here. I am curious.

Second. 
I would like to transform the code for being fully generic. Where I can overload AddConfigValidation<T>(this IServiceCollection services) to accept a second parameter, the instance of IConfiguration (or IConfigurationSection in my case) then being:  AddConfigValidation<T>(this IServiceCollection services, IConfiguration config)

And perform Configuration in the same method:
The part where I am doing:

  services.Configure<IdentityStartupSettings>(Configuration, binder => new IdentityStartupSettings());

                services.AddSingleton(resolver =>
                {
                    var identityStartupConfig = resolver.GetRequiredService<IOptions<IdentityStartupSettings>>().Value;
                    return identityStartupConfig;
                });

being inside, something like this (what is not working):

public static IServiceCollection AddConfigValidation<T>(this IServiceCollection services, IConfiguration config) 
            where T : IValidateConfig
        {
services.Configure<T>(config);

                services.AddSingleton(resolver =>
                {
                    var configValue = resolver.GetRequiredService<IOptions<T>>().Value;
                    return configValue;
                });

            services.AddTransient<IStartupFilter, ValidateConfigFilter>();

            services.AddSingleton<IValidateConfig>(provider => provider.GetRequiredService<T>());

            return services;
        }

 First error, the line services.Configure<T>(config); is asking for an Action instead of an IConfiguration instance. What is not happening when I do it outside.
Maybe you can give me some guidance.

So pleased, thanks in advance.



Why I can't change the default language of the website in asp.net core?

$
0
0

I set this in the Configure&ConfigureServices:

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddScoped<Global>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
            services.AddMvc()
                .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix,
                options => options.ResourcesPath = "Resources");
            services.AddLocalization(options => options.ResourcesPath = "Resources");
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

var SupportedCultures = new List<CultureInfo> {
new CultureInfo("en"),
new CultureInfo("zh-Hans"),
new CultureInfo("zh-Hant")
};
var options = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("zh-Hans"),
SupportedCultures = SupportedCultures,
SupportedUICultures = SupportedCultures
};
app.UseRequestLocalization(options);
var requestProvider = new RouteDataRequestCultureProvider();
options.RequestCultureProviders.Insert(0, requestProvider);
app.UseStaticFiles();

app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");



app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

I have set the 

DefaultRequestCulture = new RequestCulture("zh-Hans")

However. the website works well but the default language of the website is still English(en) but not Chinese(zh-Hans) yet.

Why it turns out to be this?

Working with .resx files programnatically in ASP.NET Core

$
0
0

Hello, I want to know if there is a way to work with .resx files programmatically like : add new ,resx file to project, edit existing .resx file or delete .resx files dynamically by code behind.

I have to mention that i don't use visual studio, I am using VSCode and as you know VSCode does not have Resource designer.

Seed Data Image

$
0
0

Hi folks,

I am using asp.net core. I want to save some photos into a database So I have created seed data for test.

In model:

    public class Image
    {
        public int ImageId { get; set; }
        public string ImageName { get; set; }
        public string ContentType { get; set; }
        public byte[] Content { get; set; }
    }

In SeedData:

    public static class SeedData
    {
        public static void Seed(this ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Image>().HasData(
                new Image { ImageId=1, Content = "???" },
                new Image { ImageId = 2, Content = "???" },
                new Image { ImageId = 3, Content = "???" }
                );
        }
    }

I have saved three photos in webapplication(project) -> Images(Folder)->(cat1.png, cat2.png, cat3.png). 
So how do i seed images?

I am waiting for your response.

Thanks in Advance!
Ref:
https://www.mikesdotnetting.com/article/259/asp-net-mvc-5-with-ef-6-working-with-files

Dropdown list - InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key

$
0
0

hi Guys,

I have this code that works in my previous projects asp.net core 2.0 and 2.2 , its a dropdownlist with auto postback

However in adding them to my recent 3.0 project I get the following errors below. Here is my code and the errors, please advise

thanks

Ehi

Error message

InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key "Cat"
<div class="col-md-3 text-center div_for_col4">
            Showing all Categories
            @Html.DropDownList("Cat", ViewBag.DepartmentID as IEnumerable<SelectListItem>, "Show all Departments", new { onchange = "form.submit();", @class = "form-control-textbox-dropdownlist" })

and controller

   ViewData["DepartmentID"] = new SelectList(_context.Set<Models.Department.Departments> (), "SubCategory_Name", "SubCategory_Name");

I don't get how to use simple href="#section" anchors on Blazor.

$
0
0

I do apologize that this sounds so NOOB, but I'm just wondering how to get this done. For some reason, oddly when first directing to a non available page and then using browser back these links do work. See my hello world example here http://testnetcorestack.quantcore360.com/

With the link we should just be able to auto scroll to the bottom. How do we substitute the simple same page <a href="#sectionid"></a> tag for blazor? 

Thanks anyone!

how to get microsoft.jQuery.Unobtrusive.Ajax

$
0
0

I tried the directions at this location, but it doesn't lead to what appears to me to be a jquery library of approximately 4k size as expected, but something else.

https://www.learnrazorpages.com/razor-pages/ajax/unobtrusive-ajax

https://github.com/aspnet/jquery-ajax-unobtrusive

I tried the package manager console and pasted in the suggested line from the link and it appears to not do anything. 

Any idea how I can get this folder?

Also, on a side note does anyone else happen to notice how there are so many things that seem to be on a steady march to the way things were done in 1985?

I found it.  The download from github does have the expected tiny file.  Not sure what the rest of the files are for.


Restrict access to Rest Api service

$
0
0
Hello I would like to have advise

I have two API services. Service A and Service B. The Service A requests Service B. I want that Service B will be accessed for only trusted services. One of them is Service A.

What way are there to implement this behavior?

What the best practices ?

Could I use IdentityServer without DB?



Requirements:

1) service B does not have DB. I can only use config file or memory of app.

2) Both services A and B doesn't have UI.



My plan:

Service A has ClientId and Client Sercret. Server A request service B by /token url and get token. After that service A will be able request service B with this token.

Maybe you can give me example of code for this scenario ?



Or there are the second solution

Asp.Net Core 2.2 ValidateAntiForgeryToken produces a 400 exception on an Ajax call

$
0
0

Hello Everyone,

In my Asp.Net Core 2.2 I have an Ajax call where I would like via Ajax to invoke ValidateAntiForgeryToken but it produces a 400 exception. Without the ValidateAntiForgeryToken the code works fine. I would appreciate any help greatly.

Thanks, kindest blessings, Andreas

View:

<divid="root"></div>

<scripttype="text/javascript">

$(function () {

$(document).ready(function () {

$.ajax({

type:"post",

contentType:"application/json",

dataType:"json",

url:"https://www.xxx.com/api/GetTagItem",

beforeSend:function (request) { request.setRequestHeader("RequestVerificationToken",$("[name='__RequestVerificationToken']").val());},

data: JSON.stringify({"Key":"News" }),

success:function (data) {

$("#root").html(data.Value);

}

});

});

});

</script>

C#:

[HttpPost]

[Route("~/api/GetTagItem")]

[ValidateAntiForgeryToken]

publicasync Task<JObject> GetTagItem([FromBody]KeyValueViewModel input)

{

……...

}

Sometimes slow response on routing

$
0
0

We have a asp.net 2.2 controller. The only thing the method does is a WCF call to an already existing service hosted in the same IIS on a different port.

We have a performance tester on a different computer which does:

1)  Do the WCF call the controller does and measuring the performance

2)  Do the controller method call measuring the performance.

It runs fast the whole night but random about 20 times per night the controller call is slow. Sometimes even 20 seconds.

The WCF call is ALWAYS fast.

Any idea?

Thanks in advance - Ton

Block Register in Asp.Net Core 2.2 Application

$
0
0

Hello Everyone,

In my Asp.Net Core 2.2 Web Application, I would like to disable the default activated opportunity to register a new user. I used the default template which implements Identity and it all works just would like for security reasons for now to prevent Registration. There is now code in my solution other than the  _LoginPartial.cshtml where I removed the register link but the problem it can still be accessed via url: https://www.xxxx.com/Identity/Account/Register

Thanks, I would appreciate any help greatly, kind blessings, Andreas

Error in Migration For Cycle

$
0
0

Hi,
In these 4 table i want create relation ,

but when i run add-migration its show this error .

Introducing FOREIGN KEY constraint 'FK_PosterGroup_tb_Feature_tb_Feature_ID' on table 'PosterGroup_tb' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

PosterGroup.cs

 public class PosterGroup
    {
        [Key]
        public int PosterGroup_Id { get; set; }
        public string PosterGroup_Title { get; set; }

        public IEnumerable<Poster> Posters { get; set; }

        public virtual IEnumerable<Feature> Feature { get; set; }

    }

Poster.cs

 public Poster()
        {

        }
        [Key]
        public int Poster_Id { get; set; }
     
        public string Title { get; set; }
    
 
        [ForeignKey("PosterGroup_Id")]

        public PosterGroup PosterGroup { get; set; }
        public int PosterGroup_Id { get; set; }


        public virtual IEnumerable<PosterFeatures> PosterFeatures { get; set; }

PosterFeature.cs 

    [Key]
        public int PosterFeature_Id { get; set; }

        [ForeignKey("Poster_Id")]

        public Poster Poster { get; set; }
        public int Poster_Id { get; set; }

        [ForeignKey("FeatureReplay_ID")]

        public FeatureReply FeatureReply { get; set; }
        public int FeatureReplay_ID { get; set; }

Feature.cs

   [Key]
        public int Feature_ID { get; set; }

     
        public Int16? ProductGroupId { get; set; }

        public string FeatureTitle { get; set; }

        public bool IsActive { get; set; }

   
        public virtual List<FeatureReply> FeatureReplies { get; set; }

        public virtual PosterGroup PosterGroup{ get; set; }
        public int? PosterGroup_Id { get; set; }

FeatureReplay.cs

  [Key]
        public int FeatureReply_ID { get; set; }
        public int FeatureId { get; set; }
        public string FeatureReplyText { get; set; }

        public virtual Feature Feature { get; set; }
    builder.Entity<Feature>().HasOne(p => p.PosterGroup).WithMany(b => b.Feature)
  .HasForeignKey(p => p.PosterGroup_Id)
  .OnDelete(DeleteBehavior.Cascade);

Whats problem ?

Core 2.2 razor pages and IIS

$
0
0

Hi,

I am working on upgrading existing Razor pages (v4.0.30319) application to asp net core 2.2 razor pages application. The application was not using routing and instead navigation to different pages was getting done using IIS rules (inbound and outbound) but it is not working with upgraded version:

Outbound rules

inbound rules

Please note that all the razor pages are at root level and not in Pages folder. Any suggestions to make it work?

Thanks in anticipation.

Assign an output paramter from a stored procedure to show in a view

$
0
0

Hi

I'm using Core 2.1 and SQL Server 2017. I want to get some output parameter value from a stored procedure and show it in a view.

I have this stored procedure which has one input and one output parameters:

ALTER PROCEDURE [dbo].[GetFDate]
@Id_p   INT,
@FDate DATETIME2 out
AS
BEGIN
    SET NOCOUNT ON;
    select @Fdate = DATEADD(DAY,SUM(DATEDIFF(DAY, SDate, EDate)), MIN(SDATE))
     from Tab1 
     where NId = @Id_p;
	 RETURN 
END

I'm trying to execute this procedure and pass parameters in the the controller like this:

    public async Task<IActionResult> GenDetails(decimal? id)
    // Some code..............
            object[] parameters =
            {
                new SqlParameter("@Id_p", id),
                new SqlParameter
                {
                    ParameterName = "@FDate",
                    SqlDbType =  System.Data.SqlDbType.VarChar,
                    Size = 9,
                    Direction = ParameterDirection.Output
                }
            };
            var FDate = await _context.Database.ExecuteSqlCommandAsync("EXEC @FDate = GetFDate @Id_p", parameters);
            ViewBag.FD = FDate;

Now I'm trying to show the reslut in the view like this:

<input type="text" value="@ViewBag.FD" />

but this sceario gives me this error:

SqlException: Procedure or function 'GetFDate' expects parameter '@FDate', which was not supplied.

Why? and how to solve please?


how to store the data into the table column as unreadable as encrypted and then decrypt the data for admin users only

$
0
0

Hi

I want to insert  the record into the table as unreadable format like encrypted format and nobody can view , read the data from the table for example bank account no. How can I keep the data in the table with proper Data security with encryption and decription

In HttpGet 

If (user= Admin)

 {

                string accountno =   BankaccountModel.AccountNo // It should be decrypted

}

In HttpPost

 {

                   BankaccountModel.AccountNo  =  accountno // It should be incrypted

}

Please help

No Parameterless Constructor Defined In Asp.net Core Web Api

$
0
0

hi,

when i want to add api and click ADD/Controller/Api using EF  
its how this error :

No parameterless constructor defined for this object

Mymodel

 public Sizes()
        {

        }  
[Key]
        public Int16 Size_ID { get; set; }
       
     
        public string SizeTitle { get; set; }

   
        public string Lang { get; set; }
     
        public Int16? ProductGroupId { get; set; }
        public virtual Language.Language Language { get; set; }
        public virtual ProductsGroup ProductsGroup { get; set; }
        public virtual IEnumerable<FactorDetails> FactorDetails { get; set; }
        public virtual List<ProductSizes> ProductSizes{ get; set; }

what's problem ?

New to .net Core from web forms and php background

$
0
0
The more I look into Core the more I am taken over with the feeling that we are going back to spaghetti code. Mixing server side functionality into client side pages. Can someone please tell me I am wrong or how this is progress?

ado.net and Entitty frame work together in a project

$
0
0

currently our application in asp.net core with ado.net . We are inserting the record and deleting the record  using the stored procedure for   insert  statement and delete statement.   So now I wan to implement entity frame work for the new program in the same project. I want to create three more program in the same project . But in the new program I want to insert and List the record using  dbcontext entity frame work.  Is it possible to use entity frame work for the rest of the program in the same project. Please can you advise me.  

Regards

Pol

Can I publish my .net core 2.1 project on a hosting server with 2.0.1

$
0
0

Hi all,

Obviously plesk doesn't have support for .net core 2.1 and at most is 2.0 there fore there is a big problem for me; how can I publish my project in a hosting service with 2.0?

thank you.

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>