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

Publishing single page from ASP.NET Core Razor project

$
0
0

I have an ASP.NET Core project using Razor pages, I published the project from Visual studio 2019 to an Azure web app, Its working fine.

But when I doing a change in a single page, I want to publish the only modified page to the host, I'm doing this from : Project menu----> Publish page.cshtml, Visual studio is telling me the file has published successfully, but I do not see any change in the online page.

Is there is any missing step after publishing the page?

Kindly help me regarding this issue.


InvalidOperationException: Unable to resolve service for type

$
0
0

Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Bumples.Controllers.AccountController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Hi, I am trying to load a very simple register program. Below are the programs involved.  I am using asp.net core mvc 3.0

Controller

<div>using System.Threading.Tasks;
using Bumples.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Bumples.ViewModels;
</div> <div>namespace Bumples.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;
</div> <div>        public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }
</div> <div>        public IActionResult Register()
        {
            return View();
        }
</div> <div>        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser
                {
                    UserName = model.Email,
                    Email = model.Email
                };
                var result = await userManager.CreateAsync(user, model.Password);
</div> <div>                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return View();
        }
    }
}
</div> <div>Model</div> <div> <div>using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
</div> <div>namespace Bumples.ViewModels
{
    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }
</div> <div>        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
</div> <div>        [Required]
        [Display(Name = "Confirm Password")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Your password and confirm password do not match")]
        public string ConfirmPassword { get; set; }
</div> <div>    }
}
</div> </div>

startup

<div>using Bumples.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
</div> <div>namespace Bumples
{
    public class Startup
    {
        private readonly IConfiguration Configuration;
</div> <div>        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
</div> <div>        public void ConfigureServices(IServiceCollection services)
        {
</div> <div>            //Add Connection Middleware   
            services.AddDbContext<ApplicationDbContext>(
                options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
</div> <div>            //Configure Identity framework core 
            services.AddIdentityCore<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                 .AddEntityFrameworkStores<ApplicationDbContext>();
</div> <div>            //Add MVC Middleware   
            services.AddControllersWithViews();
            services.AddRazorPages();
        }
</div> <div>        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
</div> <div>            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
</div> <div>            //Add Authentication and Authorization before route  
            app.UseAuthentication();
            app.UseAuthorization();
</div> <div>            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
</div> <div></div> <div>Where am I going wrong,</div> <div>Thanks Jen</div>

Is ASP.NET Core 3.1 Ready for Prime Time/Production Web Apps or Not?

$
0
0

Hi, I've been working on a web portal using ASP.NET Core 3.1 and I keep running into weird errors between Identity and EF Core. I've gone through several complete rebuilds and tons of errors and problems. when I build little web apps or separate Identity and EF Core then everything works just dandy. But when I try to bring them all together in a rather large production web app all of a sudden weird bugs crop up.
I've read that the Identity and EF Core teams work separately and sometimes there are problems between their releases...So I am wondering:

Is ASP.NET Core 3.1 not yet ready for prime time for building web apps?

Is there anyone here that is actually using it successfully in a production environment?

And if so, are there some tricks/suggestions for doing so?

Or should I use Core 2.2? Is that stable enough for production apps?

Thanks,

- Grant

ubuntu 18 + asp.net core 3.1 + apache 2.4.29 = Status Code 500/502

$
0
0

can someone help me with this issue? Sometimes i'm getting  Status Code 500/502 and i can't  find out source of this problem

.сonf file  -> sites-available

#<VirtualHost *:*>
# RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
#</VirtualHost>

<VirtualHost *:80>
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:5000/ retry=1 acquire=3000 timeout=600 Keepalive=On
ProxyPassReverse / http://127.0.0.1:5000/
ServerName www.example.com
ServerAlias *.example.com
ErrorLog ${APACHE_LOG_DIR}site-error.log
# CustomLog ${APACHE_LOG_DIR}site-access.log common
</VirtualHost>

<VirtualHost *:443>
ServerAdmin webmaster@monopoliya.net
ServerName docs.monopoliya.net
ErrorLog ${APACHE_LOG_DIR}/error.log
# CustomLog ${APACHE_LOG_DIR}/access.log combined

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

SSLEngine on
SSLProxyEngine On
SSLCertificateFile /etc/apache2/ssl/site_net.crt
SSLCertificateKeyFile /etc/apache2/ssl/site.net.key


ProxyRequests Off
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:5000/ retry=1 acquire=3000 timeout=600 Keepalive=On
ProxyPassReverse / http://127.0.0.1:5000/
</VirtualHost>




service

[Unit]
Description=site

[Service]
WorkingDirectory=/var/www

# ExecStart=/usr/share/dotnet/dotnet /var/www/site.dll
ExecStart=/usr/bin/dotnet /var/www/site.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=site
User=DotNetUser
Environment=ASPNETCORE_ENVIRONMENT=Production

[Install]
WantedBy=multi-user.target




and log

[Tue Mar 03 08:37:17.480673 2020] [proxy_http:error] [pid 52938:tid 139622659118848] (20014)Internal error (specific information not available): [client 10.75.5.126:10283] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
[Tue Mar 03 08:37:25.082441 2020] [proxy_http:error] [pid 52938:tid 139622139033344] (20014)Internal error (specific information not available): [client 10.75.5.126:10295] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
[Tue Mar 03 09:03:53.558072 2020] [proxy_http:error] [pid 52938:tid 139623095310080] (20014)Internal error (specific information not available): [client 10.75.5.126:1236] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
[Tue Mar 03 09:03:54.906938 2020] [proxy_http:error] [pid 52938:tid 139622675904256] (20014)Internal error (specific information not available): [client 10.75.5.126:1241] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
[Tue Mar 03 09:03:55.017393 2020] [proxy_http:error] [pid 52938:tid 139622642333440] (20014)Internal error (specific information not available): [client 10.75.5.126:1245] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
[Tue Mar 03 09:03:55.017506 2020] [proxy:error] [pid 52938:tid 139622642333440] [client 10.75.5.126:1245] AH00898: Error reading from remote server returned by /User/CheckAccess, referer: http://10.75.0.128/

and program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
    /*     Host.CreateDefaultBuilder(args)
             .ConfigureWebHostDefaults(webBuilder => {
               webBuilder.UseStartup<Startup>();
             });
             */

      Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => {
          webBuilder.ConfigureKestrel(serverOptions => {
            serverOptions.Limits.MaxConcurrentConnections = 500;
            serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
            serverOptions.Limits.Http2.MaxStreamsPerConnection = 200;
            //serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
            serverOptions.Limits.MinRequestBodyDataRate =
                new MinDataRate(bytesPerSecond: 100,
                    gracePeriod: TimeSpan.FromMinutes(10));
            serverOptions.Limits.MinResponseDataRate =
                new MinDataRate(bytesPerSecond: 100,
                    gracePeriod: TimeSpan.FromMinutes(10));

            serverOptions.Listen(IPAddress.Loopback, 5000);
            serverOptions.Listen(IPAddress.Loopback, 5001);
            serverOptions.Limits.KeepAliveTimeout =
                TimeSpan.FromMinutes(300);
            serverOptions.Limits.RequestHeadersTimeout =
                TimeSpan.FromMinutes(60);
            serverOptions.Limits.KeepAliveTimeout =
                TimeSpan.FromMinutes(20);
            serverOptions.Limits.RequestHeadersTimeout =
                TimeSpan.FromMinutes(10);
            serverOptions.Limits.Http2.MaxStreamsPerConnection = 100;
            serverOptions.Limits.Http2.HeaderTableSize = 4096;

          })
          .UseStartup<Startup>();
        });

    /*Host.CreateDefaultBuilder(args)
        .ConfigureServices((context, services) => {
          services.Configure<KestrelServerOptions>(
              context.Configuration.GetSection("Kestrel"));
        })
        .ConfigureWebHostDefaults(webBuilder => {
          webBuilder.UseStartup<Startup>();
        });*/
  }

PhysicalFile not returning response for range requests

$
0
0

Hey,

I have a problem delivering videos in .NET Core. I'm getting a video file by an absolute path and returning it to be used as a source in a<video> element. However, I'm enabling HTTP Range requests by passing enableRangeProcessing: true to the method, and after fast seeking through the video (once it's loaded) the action stops providing responses. The response contains exactly 16.1kb of data and does not contain any response preview or response content at all. Reloading the page after that does not help, the only thing that fixes it is rebuild and rerun again, or sometimes if you wait a while (2-3 minutes) the video loads normally on reload. Does anyone know what might be causing this?

The action in question

public IActionResult GetVideo(string path) {
    path = Uri.UnescapeDataString(path);
    return PhysicalFile(path, "application/octet-stream", enableRangeProcessing: true);
}

And here's the front-end side

<video src="@Url.Action("GetVideo", "Home", new { path = ViewBag.Id })" controls></video>

The path variable is an URI-escaped string of the absolute path in my system (for debugging purposes, it will be through IDs in the future.

How to return the Text of Selectd value of SelectList?

$
0
0

Hi

I've added new properties to the ApplicationUser Class:

    public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {
            MarkterStatus = false;
        }
        public string FullName { get; set; }
        public bool MarkterStatus { get; set; }

    }

Then child class of the previous:

    public class Orders
    {
        public int Id { get; set; }

        public string MarkterId { get; set; }

        public string MarkterName { get; set; }

        public ApplicationUser Markter { get; set; }
    }

Then I used MarkterStatus in Where to populate SelectList  like this in the controller:

            List<SelectListItem> selectList = _context.ApplicationUser.Where(x => x.MarkterStatus == true).OrderBy(x => x.FullName).Select(x => new SelectListItem { Text = x.FullName ?? "", Value = x.Id }).ToList();
            ViewData["MarkterId"] = selectList;

Now how to save the ApplicationUser.FullName text value returned by the previous SelectList in MarkterName property of Orders?

how to open javascript files that contain a magazine and games in the wwwroot

$
0
0

I am just changing over to asp.net core mvc from asp.net web.  I have a children's magazine and they go to a JavaScript file to open the mag and inside the JavaScript file are at least 30 pages and games to play.  I understand that I can't use default.aspx in wwwroot 

questions

do I make a controller for the magazines and then a model and then a view that will open the javascirpt files in the wwwroot.  That would be instead of a default aspx.

Will the JavaScript files open in the root and  can I use javascirpt files to turn the pages and games 

In the startup do I use fileupload to open the magazines in the wwwroot.

 Can I put jquery and html game files in the wwwroot

I hope someone can answer these questions

Thanks, Jen

Migrate Asp.Net Core 2.1 to 3.1

$
0
0

Hi ,

Please help me on this,

I want to migrate my WebApi project from Asp.Net Core 2.1 to 3.1.

Please give me the instruction and guideline to set up through VS Code.

Regards,

Biju


Razor Pages Vs MVC apps

$
0
0

I am wondering why Microsoft is pushing these Razor Pages Apps over MVC.
This is very annoying and concerning to me.

I'm going over the "Recommended Learning path" in the Overview at:
https://docs.microsoft.com/en-us/aspnet/core/?view=aspnetcore-3.1

It says for a new app go through the Razor Pages app.
For maintaining an app go through MVC.

Why are they pushing this Razor Pages thing?
I went through the Razor pages in the Core 2.x tutorials.
This looks like a return to the old WebForms paradigm.  Why are they doing this.
This is unclean and disgusting.  Did Microsoft learn nothing from the Web Forms era?

I try to keep the pulse on where the technology is going.
I've talked my bosses and directors into going from WebForms to MVC back in 2010.
And from Full Framework to .Net Core in 2015 and 2018 at two different places.
And if you went .Net Core Web Forms was no longer even available.  So I know I had the right pulse on the technology back in 2010.
I knew MVC would be the future and Web Forms would eventually go away.

This leaves me confused and bewildered.  I just cannot believe they are pushing this Web Forms looking crap with a separate .cs file that looks like a code behind file.
Can somebody clear this up?

What is the advantage of using Razor Pages?
Please don't answer with they are easier.
That is way to vague.

whats the max number of roles a JWT should hold?

$
0
0

Hi

Whats the max number of roles a JWT should hold?

Any advice would be appriciated.

Key Vault Secret Name to use in DB Connection string under appsettings.json

$
0
0

Hi All,

How can I get the password from Azure KeyVault > Secrets using secret name & Version to pass into Database connection string @ appsettings.json file below:-

Program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>

WebHost.CreateDefaultBuilder(args)

.ConfigureAppConfiguration((context, config) =>

{

if (context.HostingEnvironment.IsProduction())

{

var builtConfig = config.Build();

using (var store = new X509Store(StoreLocation.CurrentUser))

{

store.Open(OpenFlags.ReadOnly);

var certs = store.Certificates

.Find(X509FindType.FindByThumbprint,

 builtConfig["AzureADCertThumbprint"], false);

config.AddAzureKeyVault(

$"https://{builtConfig["KeyVaultName"]}.vault.azure.net/",

 builtConfig["AzureADApplicationId"],

certs.OfType<X509Certificate2>().Single());

store.Close();

}

}

}).UseStartup<Startup>();

Startup.cs

 public class Startup
    {
        string connectionString = "";
        string clientid = "";
        string clientsecret = "";
        string aadInstance = "";
        string tenant = "";
        public Startup(IConfiguration configuration)
        {           

            var builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
             .AddEnvironmentVariables();

            connectionString = configuration["ConnectionStrings:DefaultConnection"];

appsettings.json

{"KeyVaultName": "xxx-vault2","AzureADApplicationId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","AzureADCertThumbprint": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxx","AzureAd": {"Instance": "https://login.microsoftonline.com/","Domain": "xxxx.onmicrosoft.com","TenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","ClientSecret": "xxxxxxxx/xxxxxx/xxxxxxxxxxxxxxxx=","CallbackPath": "/signin-oidc","AuthorityFormat": "https://login.microsoftonline.com/{0}","RedirectUri": "https://xxxx.xxxx.com","GraphResourceId": "https://graph.windows.net", // This app uses the public instance of the Azure AD Graph API"GraphBaseEndpoint": "https://graph.windows.net","GraphApiVersion": "1.5"
  },"Logging": {"LogLevel": {"Default": "Warning"
    }
  },"ConnectionStrings": {"DefaultConnection": "Server=xxxxdb.database.windows.net;Database=DBNAMEHERE;Persist Security Info=False;User ID=USERIDHERE;Password=@Microsoft.KeyVault(VaultName=xxx-vault2;SecretName=KeyVaultSecretNameHere;SecretVersion=xxxxxxxxxxxxxxxxxxxxxxx);MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  },"AllowedHosts": "*"
}

Refer to appsettings.json ConnectionStrings >> DefaultConnection

Password section:
Password=@Microsoft.KeyVault(VaultName=xxx-vault2;SecretName=KeyVaultSecretNameHere;SecretVersion=xxxxxxxxxxxxxxxxxxxxxxx);

Something went wrong at the database string under appsettings.json

Please advise.

Thank you.

Regards,
Micheale

ASp.net Migration

$
0
0

Hi Expert,

how we can do box migration in .net  i mean  from physical machine  to other vm like cloning and all and what is the best approach for this like complete box would be a safest way to collect all parameter and change the domain as well

Azure AD connect is the latest one i heard about ...any other easiest one like cloud and all

Shree

checking of correct datetime format is not working

$
0
0

Hi

I want to check the given string value is correct  format for converting into  datetime  variable before to convert into date time variable.  But the value '05/03/2020 8:15:00' is showed as incorrect format . Please can you advise me where is the problem

eg: datetimestring  ='05/03/2020 8:15:00'

                string clockeddate = log.AttendanceDate;
                string timeclock = log.Hrs + ':' + log.Mins;
                string datetimestring = clockeddate + " " + timeclock+":00";

                DateTime dDate;
                bool isCorrectDateFormat =   DateTime.TryParseExact(datetimestring, "dd/MM/yyyy HH:mm:ss",
                    CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);
                if(isCorrectDateFormat)
                {
                     dDate = Convert.ToDateTime(clockeddate + " " + timeclock);
                }

A question about reading other peoples code

$
0
0

Hi

when i press f12 to navigate to a file base on the class my cursor is on, i often get to a class which is an abstract base class, how do i get to the class which actually has the implement code?

an example of this is if I implement FluentValidation and inheriate the AbstractValidator and try and view it, its shows an abstract class with no actual code, eg methods are just one line:

public ValidationResult Validate(T instance);

now that method is abstract so how do i find the code where its implemented?

This happens a lot when it navigates to classes which are not abstracted and virtual and i have no idea how to find the code.

I am mainly interested to see how its implemented so i can learn techniques, but have trouble finding the implementation.

Does SignalR have a low performance?

$
0
0

I am sorry I am a beginner.

These days I made a chatroom by asp.net core with SignalR.

My friend tried my app and pointed out that I should not use SignalR for its performance is low that now almost no one uses it.

He suggests me to use the MQ(message queue) to replace it.

However, although he has learned about not only asp.net core but also JAVA. He develops JAVA mostly in his job.

I searched in google and soon found that the Message Queuing is supported in .net framework while not supported in .net core.

I wonder whether the performance of SignalR is as low as he said.

If it was, is there any better suggestion for me to improve my project? Thank you.


ASP.NET CORE 3 Scaffolding issue not Displaying Foreign Key Data on Table Index pages

$
0
0

We recently started upgrading some of our applications from ASP.net MVC5 to ASP.NET Core 3.   We use the scaffolding tools to build the view pages for us just like we did on the original apps and then added some filtering ability.  What we have found is that the Table Indexes that have Foreign Key values are not displaying on those pages.  Once we access the CRUD pages the data is there and it works.  The Index pages worked fine in MVC5.  Does anyone know of an outstanding bug our issue with this?  I can upload our code if needed. but since we have done it on multiple applications I suspected it might be a known issue.

Thanks.

Creating A Global Model, With No Associated Database Table

$
0
0

Hello All,

I am using ASP .Net Core 3.1 Razor Pages (non-MVC) with Entity Framework Core.

Consider the following OnGet() Handler in an Index.cs file:

public IActionResult OnGet()
{
var webRootPath = _hostingEnvironment.WebRootPath;
var docsPath = Path.Combine(webRootPath, "documents");

var DocumentInformation = Directory.GetFiles(docsPath, "*.*", SearchOption.TopDirectoryOnly);

return Page();
}

This code returns an array of files in the wwwroot/documents directory.

This array is read into the local variable  var DocumentInformation

My question:

Instead of using a local variable, I would like to create a model, that can not only be passed back to the .cshtml file, but can be used in other parts of my application.

I don't want the model to be used to create a database table.

I would appreciate any guidance on how to accomplish this.

Thanks in advance for your time....

Validate inputs when submitting

$
0
0

Hi people,

I am with a problem in my SignIn page.
In my page, I have a form with two inputs and I want to validate if both are filled before submitting but if I put a handler in my form, it prevents my submission.

My HTML code:

<form action="Authentication/SignIn" method="post" @onsubmit="HandleSubmit"><Input @ref="_usernameInput" Type="text" Name="username" @bind-Value="_username" Placeholder="@Resource.key_397" Autocomplete=false Autofocus=true Error="@Resource.key_196" HandleFocus="HandleUsernameFocus" /><Input @ref="_passwordInput" Type="password" Name="username" @bind-Value="_password" Placeholder="@Resource.key_314" Autocomplete=false Autofocus=false Error="@Resource.key_195" HandleFocus="HandlePasswordFocus" /><KeyPad Class="signin-keypad" HandleButton="HandleButton" /><button type="submit" class="hide" /></form>

My handler:

private void HandleSubmit()
{
    int a = 0;
}

I am using .NET Core 3.1 | Visual Studio 2019 Version 16.4 | 3.1.1

asp core 3.1 identity login dowesn't work and shows samesite warning

$
0
0
<div>I just finished my asp .net core 3.1 project. and i was trying to deploy it onIIS. So first i scaffolded Asp Identity and it createdidentityHostingStartup and other files. And published the project as self-Contained forwin-x64  as  I generated self signed certificate using openssl for Identity using this process </div> <div> https://benjii.me/2017/06/creating-self-signed-certificate-identity-server-azure/ and put it inside publish folder.also i have used No managed code for the app pool when i tested it, the login it worked on some machines on chrome but for those it didn't work on,it still worked on Microsoft edge browser. when i inspected the login, it shows a warning "a cookie associated with the resource was set with samesite==none" and the warning disappears instantly.But the request was sent with a cookie with value"samesite= strict" and not secure. So i modified startup.cs as shown and set samesite property to none but it didn't work. </div> <div> </div> <div>Here is the code for **startup.cs** </div> <div>
       public void ConfigureServices(IServiceCollection services)        {            X509Certificate2 cert = null;            using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))            {                certStore.Open(OpenFlags.ReadOnly);                X509Certificate2Collection certCollection = certStore.Certificates.Find(                    X509FindType.FindByThumbprint,                    // Replace below with your cert's thumbprint                    "418f13d9473b6412e186f8e3a05fbf0370ec865c",                    false);                // Get the first cert with the thumbprint                if (certCollection.Count > 0)                {                    cert = certCollection[0];                    //Log.Logger.Information($"Successfully loaded cert from registry: {cert.Thumbprint}");                }            }            // Fallback to local file for development            if (cert == null)            {                cert = new X509Certificate2(Path.Combine("C:\\inetpub\\wwwroot\\VatAppPublish\\", "localhost.pfx"), "");               // Log.Logger.Information($"Falling back to cert from file. Successfully loaded: {cert.Thumbprint}");            }                       services.AddDbContext<vat_dbContext>(options =>                options.UseMySql(                    Configuration.GetConnectionString("DefaultConnection")));            services.AddDbContext<ApplicationDbContext>(options =>               options.UseMySql(                   Configuration.GetConnectionString("DefaultConnection")));            services.AddMvc(option => option.EnableEndpointRouting = false)                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)                .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)                .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());            services.AddAuthentication(IISDefaults.AuthenticationScheme);            services.AddTransient<CompanyBLLCustom>();            services.AddTransient<CustomerBLLCustom>();            services.AddTransient<MachinesalesBLLCustom>();            services.AddTransient<ManualsalesBLLCustom>();            services.AddTransient<PurchaseBLLCustom>();            services.AddTransient<SummaryreportsBLLCustom>();            services.AddTransient<SystemconfigBLLCustom>();            services.AddTransient<SalesreportBLLCustom>();            services.AddTransient<PurchasereportBLLCustom>();            services.AddTransient<CompanyFunctions>();            services.AddTransient<CustomerFunctions>();            services.AddTransient<MachinesalesFunctions>();            services.AddTransient<ManualsalesFunctions>();            services.AddTransient<PurchaseFunctions>();            services.AddTransient<SystemconfigFunctions>();            services.AddTransient<SummaryreportsFunctions>();            services.AddTransient<SalesreportFunctions>();            services.AddTransient<PurchasereportFunctions>();            services.AddTransient<CompanyValidator>();            services.AddTransient<CustomerValidator>();            services.AddTransient<MachinesalesValidator>();            services.AddTransient<ManualsalesValidator>();            services.AddTransient<PurchaseValidator>();            services.AddTransient<SummaryreportsValidator>();            services.AddTransient<SystemconfigValidator>();            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)                .AddEntityFrameworkStores<ApplicationDbContext>();            services.AddIdentityServer()                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>()                .AddSigningCredential(cert); ;            services.Configure<CookiePolicyOptions>(options =>            {                options.MinimumSameSitePolicy = SameSiteMode.None;            });            services.AddAuthentication()                .AddIdentityServerJwt();            services.AddControllersWithViews();            services.AddRazorPages();            // In production, the React files will be served from this directory            services.AddSpaStaticFiles(configuration =>            {                configuration.RootPath = "ClientApp/build";            });        }        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        {            app.UseAuthentication();            app.UseIdentityServer();                      app.UseHttpsRedirection();            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();                app.UseDatabaseErrorPage();            }            else            {                app.UseExceptionHandler("/Error");                // 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.UseStaticFiles();            app.UseSpaStaticFiles();            app.UseRouting();            app.UseAuthorization();            app.UseEndpoints(endpoints =>            {                endpoints.MapControllerRoute(                    name: "default",                    pattern: "{controller}/{action=Index}/{id?}");                endpoints.MapRazorPages();            });            app.UseSpa(spa =>            {                spa.Options.SourcePath = "ClientApp";                if (env.IsDevelopment())                {                    spa.UseReactDevelopmentServer(npmScript: "start");                }            });            app.UseCookiePolicy(new CookiePolicyOptions            {                MinimumSameSitePolicy = SameSiteMode.None            });
```
*** appseting.json***
```{  "ConnectionStrings": {    "DefaultConnection": "Server=localhost;Port=3306;User=root;Password='';Database=vat_db;TreatTinyAsBoolean=true"  },  "Logging": {    "LogLevel": {      "Default": "Information",      "Microsoft": "Warning",      "Microsoft.Hosting.Lifetime": "Information"    }  },  "IdentityServer": {    "Clients": {      "VatApplication": {        "Profile": "IdentityServerSPA"      }    }    ,    "Key": {      "Type": "File",      "FilePath": "C:\\inetpub\\wwwroot\\VatAppPublish\\localhost.pfx",      "Password": ""    }  },  "AllowedHosts": "*"
}
```
**IdentityHostingStartup.CS**
```public class IdentityHostingStartup : IHostingStartup    {        public void Configure(IWebHostBuilder builder)        {            builder.ConfigureServices((context, services) => {            });        }    }

</div> <div>Thank you in Advance.</div>

How would be possible to replace JsonResult with IAction method on the given code

$
0
0

Just I am looking for to replace the JsonResult method into IAction   in the code given below

Javascript
function GetClockList() {
            try {

                var table = $('#tblData').DataTable();
                table.destroy();
            }
            catch (ex) {

            }

            var table=  $('#tblData').DataTable({"ajax": {"url": "/Home/GetClockList?employeeid=" + $('#dropdownEmployee').val()+ "&clockdate=" + $('#txtAttendanceDate').val() ,"type": "GET","datatype": "json","dataSrc": function (json) {
                        return JSON.parse(json);
                    }
                 },"columns": [
                    { "data": 'ID', "width": "6%" },
                    { "data": 'EmployeeName', "width": "20%" },
                    { "data": 'ClockedDatetoList', "width": "20%" },

                ],
                
                "language": {"emptyTable": "no data found."
                },"width": "100%"
            });




        }
Controller -- Here how can I replace JsonResult with public IAction method

 public JsonResult GetClockList(int employeeid,string clockdate) // Is it possible replace JsonResult with IActionResult, If so please how can I
        {
            DateTime _clockdate = Convert.ToDateTime(clockdate);
            ICollection<EsslLog> EsslLog = new List<EsslLog>();
            EsslLog = _unitOfWork.EsslLogRepo.GetClockList(employeeid.ToString(), _clockdate);
            String jsonResult = JsonConvert.SerializeObject(EsslLog);
            return Json(jsonResult);          
        }


Repository

public ICollection<EmpLog> GetClockList(string empcode, DateTime datefrom)
        {
            ICollection<EmpLog> data = new List<EmpLog>();
            data = (from log in ctx.EsslLogs
                    join emp in ctx.goEmployee on log.EmpCode equals emp.EmployeeID.ToString()
                    where log.EmpCode==empcode&& log.DateWithoutTime == datefrom
                    select new EsslLog
                    { 
                        ID = log.ID,
                        EmpCode = emp.EmployeeID.ToString(),
                        EmployeeName=emp.EmployeeName,
                        ClockedDate = log.ClockedDate,
                        ClockedDatetoList =   log.ClockedDate.Value.ToString("dd/MM/yyyy HH:mm:ss")
                    }
                    ).ToList();
            return data;
        }

Viewing all 9386 articles
Browse latest View live


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