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

Fake dll support in .net core

$
0
0
<div style="background-color: #ddd; border-left: solid 5px #999999; margin: 15px; margin-left: 30px; width: 95%;"> <div style="border: solid 10px #ddd;">

Hi Team,

I am doing a migration asp.net project 4.5 frameworks to asp.net core 3.1

I can see fake dll is used in 4.5 framework so this is feature of Visual studio enterprise edition inasp.net core also we can generate fake dll

so want to know is fake dll is supported in .net core?

any suggestion and help will be highly appreciated on how to proceed further on this.
Regards

</div> </div>

Unable to track if the user accept the privacy message using HttpContext.Features.Get

$
0
0

I am working on an asp.net MVC 3.1 web application,and i follow the steps inside this link to activate showing a privacy message @ https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-3.1 .

now inside my Action Method, i want to check if the user accept the privacy alert or not, i tried the following code:-

var consentFeature = HttpContext.Features.Get<ITrackingConsentFeature>();
var canTrack = !consentFeature?.CanTrack ?? false;

but the canTrack will always be false, even if the user accepts the privacy alert. any advice on this please? Thanks

just starting out, Razor or MVC

$
0
0

I'm just starting out in .NET core, I did a CRUD microservice and API already and now I'm looking to build a ASP.NET CORE Web App. I'm seeing tutorials using Razor pages and MVC way, which is the preferred and does one have more value then the other? 

SignalR .Core Streaming Size Limitation (~70K Bytes)

$
0
0

Hello everybody,

we have developed an ASP.NET Core (3.1) SignalR Server. A Unity client connects to the Server and starts streaming an image to the server. The image is streamed by computing a bytes array and creating small packages. Each package contains maximal 6000 bytes. These packages are then processed by the server and sent directly to another client (see code sample on the bottom). 

When we run everything on my local machine - everything works fine. When we run the server on another machine but in the same network - everything still works. However, when we run the server in a different network, the connection between the server and the client gets lost - but only when we try to send an image bigger than ~70K Bytes. 

We already tried to change the limiation properties on the server like: 

-MaximumReceiveMessageSize 
-  StreamBufferCapacity
- ApplicationMaxBufferSize
- TransportMaxBufferSize

However, nothing worked so far. Furthermore, we also checked the ISS configuration but did not found anything. 

As Hub Protocoll we use MessagePack. Neither the server nor the client throw any kind of error message. The signalR connection gets instantly lost. Furthermore, the connection handler on the client side does not even  get informed that the state of the connection has changed.

Here is the example code we use on the client (SignalR Core with BestHTTP2): 

 public void stream(byte[] imgBytes)
    {
       int imgBufferSize = 6000;

       using (var controller = this.host3DHub.GetUpStreamController<string, string>("Stream"))
        {
            controller.OnSuccess(_ =>
            {
                Console.Log("Stream finished");
                controller.Cancel();
            });
            controller.OnError(error =>
            {
                Console.Log("Streaming failed. Error: " + error);
                controller.Cancel();
            });
            for (var i = 0; i < imgBytes.Length; i = i + imgBufferSize)
            {

                int lengthArr = (i + imgBufferSize >= imgBytes.Length) ? imgBytes.Length - i : imgBufferSize;
                byte[] imgChunk = new byte[lengthArr];
                Array.Copy(imgBytes, i, imgChunk, 0, lengthArr);
                controller.UploadParam(imgChunk);
            }
            controller.Finish();
        }
    }

The corresponding Code on the Host is: 

public async Task Streaming(IAsyncEnumerable<byte[]> stream)
{
    try{
if (connectedClients.ContainsKey(Context.ConnectionId)){ Client client = connectedClients[Context.ConnectionId]; await foreach (var item in stream) { Clients.OthersInGroup(divaNr).SendAsync("newRenderChunk", item); } } }catch(System.Exception e){ Console.Log("StreamRendering", "Error during streaming chunks. E: " + e.Message); }
}

 

If anybody can help us or give us a hint what we can test? Thanks already in advance!

Lea

Cookie autentication is not valid after login

$
0
0

Hi

I use asp net core mvc 3.1, with cookie autentication..

But when I add [Authorize] in each control, it redirect to login althought the browser send the cookie.

I followed this link...

https://www.c-sharpcorner.com/article/cookie-authentication-in-net-core-3-0/

This is the startup class:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Pronabec.IES_EXTRANET_INTERNO.Presentation.SITE.Filters;
using Pronabec.IES_EXTRANET_INTERNO.Presentation.Util.Dto;
using ServiceReferenceTarifario;

namespace Pronabec.IES_EXTRANET_INTERNO.Presentation.SITE
{
    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(
                 options => options.Filters.Add(new PronabecErrorAttribute())
                 );
            //.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            //.AddNewtonsoftJson();

            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "CookieAuthentication";
                    options.RequireAuthenticatedSignIn = false;
                })
               .AddCookie("CookieAuthentication", config =>
               {
                   config.Cookie.Name = "UserLoginCookie";
                   config.LoginPath = "/Account/Login";
                   config.SlidingExpiration = true;
               });

            //services.AddAuthentication("CookieAuthentication")
            //  .AddCookie("CookieAuthentication", config =>
            //  {
            //      config.Cookie.Name = "UserLoginCookie";
            //      config.LoginPath = "/Account/Login";
            //  });


            services.AddControllersWithViews();

            services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
            services.AddSession();

            services.AddSingleton(x => new ServiciosDto
            {
                TarifarioUrl = Configuration["UrlServicios:Tarifario"],
                MaestrosUrl = Configuration["UrlServicios:Maestros"],
                SeguridadUrl = Configuration["UrlServicios:Seguridad"],
                ImagenUrl = Configuration["UrlServicios:Imagen"],
                UsuarioUrl = Configuration["UrlServicios:Usuario"],
                ArchivosUrl = Configuration["UrlServicios:Archivo"]
            });

            services.AddSingleton(x => new AppSettingsDto
            {
                IdSistema = Configuration["AppSettings:ID_SISTEMA"]
            });

            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();


        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule(new ApplicationModule());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSession();

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(
            //    Path.Combine(Directory.GetCurrentDirectory(), "Content")),
            //    RequestPath = "/Content"
            //});

            //app.UseDirectoryBrowser(new DirectoryBrowserOptions
            //{
            //    FileProvider = new PhysicalFileProvider(
            //Path.Combine(Directory.GetCurrentDirectory(), "Content")),
            //    RequestPath = "/Content"
            //});

            app.UseRouting();

            // who are you?  
            app.UseAuthentication();

            // are you allowed?  
            app.UseAuthorization();


            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllerRoute(
            //        name: "default",
            //        pattern: "{controller=Account}/{action=Login}/{id?}");
            //});

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Account}/{action=Login}/{id?}");
            });


        }
    }
}

The method which creates the cookie...

   var identity = new System.Security.Claims.ClaimsIdentity(new[] { 
                new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, Username) });

            var nameSis = appSettingsDto.IdSistema;
            var objUser = await agenteSeguridad.getRoles(Username, nameSis);

            foreach (var rol_ in objUser)
            {
                identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, rol_.Name));
            }

            var principal = new System.Security.Claims.ClaimsPrincipal(identity);

            await HttpContext.SignInAsync("CookieAuthentication", principal);

I can get the values of the cookie but I have to write "anonymous" in each method..

        [HttpGet]
        [AllowAnonymous]
        public ActionResult RedirectToDefault()
        {

            var userIdentity = (System.Security.Claims.ClaimsIdentity)HttpContext.User.Identity;
            var claims = userIdentity.Claims;
            var roleClaimType = userIdentity.RoleClaimType;
            var rolesc = claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Role).ToList();
            String[] roles = rolesc.Select(c => c.Value).ToArray();


            if (roles.Contains("ADMINISTRADOR-IES/CF"))
            {
                return RedirectToAction("Index", "Home");
            }
            if (roles.Contains("ADMINISTRADOR-PRONABEC"))
            {
                return RedirectToAction("Index_admin", "Home");
            }


            return RedirectToAction("Index", "Home");
        }

But If I write [Authorize] in a method, the web is redirect to the login..

How to implement Sort Filter Page and Group using a view Model

$
0
0

I am trying to follow this ASP Core tutorial : https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/sort-filter-page?view=aspnetcore-3.1

however I am trying to use a view model and encountering numerous issues with making the changes, i think its something to do with PaginatedList customised to handle only type Routine from the DB and not the view model version but im not sure why.

The current error im facing is InvalidOperationException: Include has been used on non entity queryable.

TroydonFitnessWebsite.Models.PaginatedList<T>.CreateAsync(IQueryable<T> source, int pageIndex, int pageSize) in PaginatedList.cs
+
var count = await source.CountAsync();
TroydonFitnessWebsite.Pages.Products.TrainingRoutines.IndexModel.OnGetAsync(string sortOrder, string currentFilter, string searchString, Nullable<int> pageIndex) in Index.cshtml.cs
+
TrainingRoutineVMs = await PaginatedList<TrainingRoutineVM>.CreateAsync(

This is the PaginatedList.cs sample from the website:

namespace ContosoUniversity
{
    public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);

            this.AddRange(items);
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex < TotalPages);
            }
        }

        public static async Task<PaginatedList<T>> CreateAsync(
            IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip(
                (pageIndex - 1) * pageSize)
                .Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }
    }
}

And here is my classes that I am implementing with it:

namespace FitnessWebsite.Pages.Products.Trainings
{
    public class IndexModel : FilterSortModel
    {
        private readonly ProductContext _context;

        public IndexModel(ProductContext context)
        {
            _context = context;
        }
        public PaginatedList<TrainingVM> TrainingVMs { get; set; }


        public async Task OnGetAsync(string sortOrder,
            string currentFilter, string searchString, int? pageIndex)
        {
            // assign hard prefix values
            AssigningSortOrderValues(sortOrder);

            if (searchString != null)
            {
                pageIndex = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            CurrentFilter = searchString;
            CurrentSort = sortOrder;

            IQueryable<TrainingVM> trIQ = (IQueryable<TrainingVM>)(from s in _context.Trainings
                                                             select new TrainingVM();

            if (!String.IsNullOrEmpty(searchString))
            {
                trIQ = trIQ.Where(tr => tr.PersonalTrainingSession.Product.Title.Contains(searchString.ToUpper()) ||
                tr.PersonalTrainingSession.Product.ShortDescription.Contains(searchString.ToUpper())
                || tr.Description.Contains(searchString.ToUpper()));
            }

            trIQ = (IQueryable<TrainingVM>)DetermineSortOrder(sortOrder, trIQ);

            int pageSize = 5;

            TrainingVMs = await PaginatedList<TrainingVM>.CreateAsync(
               trIQ
               .Include(tr => tr.PersonalTrainingSession.Product)
               .ThenInclude(tr => tr.PersonalTrainingSessions)
               //.AsNoTracking()
               ,pageIndex ?? 1, pageSize);
        }
        private static IQueryable DetermineSortOrder(string sortOrder, IQueryable<TrainingVM> trIQ)
        {
            switch (sortOrder)
            {
                case "id_asc":
                    trIQ = trIQ.OrderBy(s => s.PersonalTrainingSession.ProdID);
                    break;
                case "id_desc":
                    trIQ = trIQ.OrderByDescending(s => s.PersonalTrainingSession.ProdID);
                    break;
            }
            return trIQ;
        }

In SortFIlterClass

  public void AssigningSortOrderValues(string sortOrder)
        {
            IdSort = sortOrder == "id_asc" ? "id_desc" : "id_asc";
        }

Strategy for Shopping Cart (.Net Core 3.1 MVC)

$
0
0

Hi. I'm very new coding, so the most practical & easy solution will be fine for my by now.

I'm doing a very vanilla net core 3.1 mvc academic project and I need to implement a shopping cart.

My involved Models are:

  • Order, that contains a collection of
  • LineOrder which is linked with one
  • Instrument (an Instrument can be linked to many LineOrders on differents Orders).

My Uses Cases are 2:

  • In the Homepage you can "Add to Cart" an Instrument, which has to be added to cart with the quantity of 1 & default attributes.
  • In the Instrument/Details you can select different product attributes and the quantity of items and then "Add to Cart".

In both cases I suppose I have to use ajax requests.

If the user is authenticated the cart has to be loaded (If the purchase isn't completed). I guess I will need some init rutine to load or create the cart.

On the navbar I have a counter that has to show the nº of items in the cart.

I see at least 3 differents aproaches but I don't know which one could I use( I accept new ones):

  1. Cart logic inside Order/Details Controller & custom methods(add,remove to cart, load etc). A cart would be an Order withStatus property as "Cart" until payment is made whose Status changes to "processing".
  2. Cart logic on dedicated CartController. I would only  use a CartDetails View, but I would make POST request to it's methods.
  3. Cart Class(that you injects at required place) works with Order, LineOrders & Instrument Models and I don't know if use Interface like CartService. (very few experience with that).

I remember that I don't have so much experience (I messed up beyond scaffolded Model > Controller > View) and the simplest and closest solution to the vanilla project, will be fine for me. 

Thanks in advance.

Hide / Show ASP.NET Core HTML Tags

$
0
0
@if (TempData["fnOutput"] == true)
                    {<span id="fnoutput"></span>
                    }

I want to hide / show HTML tags based on the bool value in TempData. Similarly, I tried with ViewBag and it doesn't return a result. How can I hide / show HTML tags without using Javascript?


linq-to-twitter Twitter flood get

$
0
0

Hi everyone,

I tried the code below but again it wasn't exactly as I wanted. Only 1 pearl flood is coming.

There are 90 floods. RT ones should not come and should only come flood by call.

as an example I shared the picture. What do I have to do in this situation.

I did but I have Count=0. Why ?

There is registration on this site. How this site does it. Do you know below website.

https://threadreaderapp.com/search?q=HANEDANLAR+MASASININ+YER+ALTI+EGEMENL%C4%B0%C4%9E%C4%B0%3AR%C4%B0O+T%C4%B0NTO

const int MaxSearchEntriesToReturn = 100;
        const int SearchRateLimit = 180;
var myFilter = "-filter:retweets"; string searchTerm = "HANEDANLAR MASASININ YER ALTI EGEMENLİĞİ:RİO TİNTO " + myFilter; // oldest id you already have for this search term ulong sinceID = 1; // used after the first query to track current session ulong maxID; var combinedSearchResults = new List<Status>(); List<Status> searchResponse = await (from search in ctx.Search where search.Type == SearchType.Search && search.Query == searchTerm && search.Count == MaxSearchEntriesToReturn && search.SinceID == sinceID && search.TweetMode == TweetMode.Extended select search.Statuses) .SingleOrDefaultAsync(); if (searchResponse != null) { combinedSearchResults.AddRange(searchResponse); ulong previousMaxID = ulong.MaxValue; do { // one less than the newest id you've just queried maxID = searchResponse.Min(status => status.StatusID) - 1; Debug.Assert(maxID < previousMaxID); previousMaxID = maxID; searchResponse = await (from search in ctx.Search where search.Type == SearchType.Search && search.Query == searchTerm && search.Count == MaxSearchEntriesToReturn && search.MaxID == maxID && search.SinceID == sinceID && search.TweetMode == TweetMode.Extended select search.Statuses) .SingleOrDefaultAsync(); combinedSearchResults.AddRange(searchResponse); } while (searchResponse.Any() && combinedSearchResults.Count < SearchRateLimit); combinedSearchResults.ForEach(tweet => Console.WriteLine("\n User: {0} ({1})\n Tweet: {2}", tweet.User.ScreenNameResponse, tweet.User.UserIDResponse, tweet.Text ?? tweet.FullText) ); } else { Console.WriteLine("No entries found."); } ViewBag.Twet = combinedSearchResults.ToList();

Some services are not able to be constructed Error is coming in program.cs please help to fix

$
0
0

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType in program.cs

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;

namespace MyWeather
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

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

My code is given below

Interface

using MyWeather.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyWeather.Repository.IRepository
{
    public interface IWeatherRepository
    {
        Task<IEnumerable<Weather>> GetWeatherAsync();
    }
}

Repo

using MyWeather.Models;
using MyWeather.Repository.IRepository;
using MyWeather.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace MyWeather.Repository
{
    public class WeatherRepository : IWeatherRepository
    {
        private readonly IHttpClientFactory _clientFactory;
        public WeatherRepository(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }
        public async Task<IEnumerable<Weather>> GetWeatherAsync()
        {
            var url = SD.APILocationUrl;
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request);
            IEnumerable<Weather> weather = new List<Weather>();
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<IEnumerable<Weather>>(jsonString);
            }
            return null;
        }

    }
}

startup.cs
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddScoped<IUnitOfWork,UnitOfWork>();
            services.AddScoped<IWeatherRepository, WeatherRepository>();
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddRazorPages();
        }

Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MyWeather.Models;
using MyWeather.Repository.IRepository;
using Microsoft.AspNetCore.Mvc;

namespace MyWeather.Areas.Customer.Controllers
{
    [Area("Customer")]
    public class ForcastController : Controller
    {
        private readonly IWeatherRepository _weatherRepository;
        public Weather Weather { get; set; }
        public ForcastController(IWeatherRepository weatherRepository)
        {
            _weatherRepository = weatherRepository;
        }
        public async Task<IActionResult> Index()
        {
            var Weather = new List<Weather>();
            var weatherList = await _weatherRepository.GetWeatherAsync();
            return View();
        }
    }
}


Weather.Repository.IRepository.IWeatherRepository Lifetime: Scoped ImplementationType:

My code

How to read proxy setting ipv4/ipv6 in dotnet core ubuntu

$
0
0

Hi Experts,

please let me know how i can read proxy settings in ubuntu 20.04.

also how i can get the bypass list from the proxy settings.

please provide me snippet of code for the above.

Thanks in advance,

KK

Creating an Endpoint that can read any json. A generic endpoint API

$
0
0

So I have a requirement to have one endpoint that can read json payload that can hit it from different system. We have several partners that would be posting data to our system.  So we want one endpoint that would handle getting data from any of our partners posting data.

I have something like this already.

[HttpPost]
public string Getdata([FromBody]Object data)
{

  //how do I convert it to the specific class that sooths the  json payload.

  //Or how do I read the data attribute of the object data pasted without knowing the payload structure.
}

I need to be able to create a generic json reader like this system here

https://quicktype.io/csharp/

So when data hits me I can read the data.

Best Regards,

Thanks in Advance

Jquery datepicker is not showing please help

$
0
0

Here is my code. I have given my model, controller, view please help

Model
public class WeatherVM
    {
        public int LocationId { get; set; }
        public DateTime ForcastDate { get; set; }
        public WeatherLocation WeatherLocation;
        public IEnumerable<Weather> Weather { get; set; }
        public IEnumerable<SelectListItem> Locations { get; set; }

    }
Controller

 public async Task<IActionResult> Index()
        {
            IEnumerable<WeatherLocation> locList = _unitOfWork.Location.GetAll();

            WeatherVM weatherVM = new WeatherVM()
            
            {
                
                Locations = locList.Select(i => new SelectListItem
                {
                    Text = i.LocationName,
                    Value = i.LocationId.ToString()
                })
            };
            weatherVM.ForcastDate= DateTime.Now;

            //var Weather = new List<Weather>();
            //var weatherList = await _weatherRepository.GetWeatherAsync();

            return View(weatherVM);
        }

View

@model myWeather.ViewModels.WeatherVM
@{
    ViewData["Title"] = "Index";
}<h1>Forcast Weather </h1><form asp-controller="Forcast" asp-action="Index" method="post"><div class="form-group"><div class="row"><div class="col-sm-2"><label asp-for="Locations">Locations</label></div><div class="col-4">
                @Html.DropDownListFor(m => m.WeatherLocation.LocationId, Model.Locations, "-Select a Category",
                new { @class = "form-control" })</div></div></div><div class="form-group row"><div class="col-sm-2"><label asp-for="ForcastDate"></label></div><div class="col-4"><div class='input-group date' id='startDatePicker'><input type='text' id="forcastDate"  asp-for="ForcastDate" readonly class="form-control" /><span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div><span asp-validation-for="ForcastDate" class="text-danger"></span></div></div></form><script type="text/javascript">$(document).ready(function () {
        KeyHandler();$("#startDatePicker").datepicker({ format: 'dd/mm/yyyy', date: new Date(1900, 01, 01), autoclose: true, todayBtn: 'linked' });

    });



 


</script>

Layout

<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>@ViewData["Title"] - MetaWeather</title><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /><link rel="stylesheet" href="~/css/site.css" /><link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" /></head><script src="~/lib/jquery/dist/jquery.min.js"></script><script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script><script src="~/js/site.js" asp-append-version="true"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script><script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script><script src="https://kit.fontawesome.com/e19c476714.js"></script>

Please help urgent , Value is not coming into the post action from the model

$
0
0

My Model class

 public class WeatherVM
    {
        public int LocationId { get; set; }
        public DateTime ForcastDate { get; set; }
        public WeatherLocation WeatherLocation;
        public IEnumerable<Weather> Weather { get; set; }
        public IEnumerable<SelectListItem> Locations { get; set; }

    }

public class WeatherLocation
    {
        [Key]
        public int LocationId { get; set; }
        [Required]
        public string LocationName { get; set; }
        [Required]
        public string Woeid { get; set; }
    }

View

@model MetaWeather.ViewModels.WeatherVM
@{
    ViewData["Title"] = "Index";
}<h1>Forcast Weather </h1><form asp-controller="Forcast" asp-action="Index" method="post"><div class="form-group"><div class="row"><div class="col-sm-2"><label asp-for="Locations">Locations</label></div><div class="col-4">
                @Html.DropDownListFor(m => m.WeatherLocation.LocationId, Model.Locations, "-Select a Location",
                new { @class = "form-control" })<span asp-validation-for="WeatherLocation.LocationId" class="text-danger"></span></div></div></div><div class="form-group row"><div class="col-sm-2"><label asp-for="ForcastDate"></label></div><div class="col-4"><input type='text' id="forcastDate" asp-for="ForcastDate" class="form-control" /><span asp-validation-for="ForcastDate" class="text-danger"></span></div><br /><input type="submit" value="Save" class="btn-sm btn btn-primary" /></div><div class="form-group row"><div class="col-4 offset-4"><button type="submit" class="btn btn-primary form-control"> View</button></div></div></form>
@section Scripts{<script>$(document).ready(function () {$("#forcastDate").datepicker({ format: 'dd/mm/yyyy', date: new Date(1900, 01, 01), autoclose: true, todayBtn: 'linked' });

        });
    </script>
}

Controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Index(WeatherVM weatherVM) // Selected Region is not coming here. How can I pass Location Id
        {
            return View();
        }

Active Directory authentication and additional metadata related to the user.

$
0
0

Hello, I'm new around here.

I'm looking at making a NET CORE web app for my workplace. The idea is that the users have to be authorized by our organizational Azure Active Directory (AD) single sign-on.
I did a quick test by making an app that has "Work or School Account" authentication and it worked surprisingly well. When running the app it requires the login and all that. 

However, I also would like to have roles inside the app, and these roles are stored in the app, not in AD. I also want to be able to see when a specific user has logged in etc. The function of these roles is to different access among the users, such as Admin, Manager etc. So there will be pages that are only accessed by certain roles. So I need to know how the current user is and then compare it to a table that holds their email and permission group. Perhaps fetching this when the user logs in and store it in a variable for faster access. 

I was thinking of making a system that takes the email from the currently logged in user and looks up the email in a table that holds the roles. But then I would also need to build a system to check if a user has this access on every page. So maybe there is a simpler way of doing this, or maybe even a build-in framework that I can use to do these things. I'm trying to find an easy way to do this, it does not need too many features beyond this. 


So in short AD is used to authenticate the users (only users from our org will be able to access), but the app will hold some additional information on this user, such as permission. 

I also wonder how the best way to get the user email from a logged-in user is, I noticed that using @User.Identity.Name shows an email, but is it reliable? 
As a test, I tried creating a static method to fetch this information, but it seems to be very slow and sometimes it shows up empty. 

        public static string getEmail()
        {
            return UserPrincipal.Current.EmailAddress;
        }

Does anyone have any ideas on how the best way to proceed?


Web Service running on port 80 required admin password

$
0
0

Hi Experts,

I have created a soap service using dotnet core SoapCore module.

This service i am trying to run in the port 80. If i want to run service password is required.

Is there any possibility to run service without providing admin password to run soap service service.

Please share me snippet of code if possible.

Thanks in advance,

KK

how can I remove the time part from datepicker. When the page load , the time part is also showing

$
0
0

how can I remove the time part from datepicker. When the page load , the time part is also showing

Controller
 public async Task<IActionResult> Index()
        {
            IEnumerable<WeatherLocation> locList = _unitOfWork.Location.GetAll();

            WeatherVM weatherVM = new WeatherVM()
            {
                
                Locations = locList.Select(i => new SelectListItem
                {
                    Text = i.LocationName,
                    Value = i.LocationId.ToString()
                })
            };
            weatherVM.ForcastDate= DateTime.Now;

            //var Weather = new List<Weather>();
            //var weatherList = await _weatherRepository.GetWeatherAsync();

            return View(weatherVM);
        }

View
<div class="form-group row"><div class="col-sm-2"><label asp-for="ForcastDate"></label></div><div class="col-4"><input type='text' id="forcastDate" asp-for="ForcastDate"  class="form-control" /><span asp-validation-for="ForcastDate" class="text-danger"></span></div></div></form>
@section Scripts{<script>
        alert("alkds");$(document).ready(function () {$("#forcastDate").datepicker({ format: 'dd/mm/yyyy', date: new Date(1900, 01, 01), autoclose: true, todayBtn: 'linked' });

        });
    </script>
}

System.NullReferenceException: 'Object reference not set to an instance of an object.'

$
0
0

My view

<div class="form-group"><div class="row"><div class="col-sm-2"><label asp-for="Locations">Locations</label></div><div class="col-4">
                @Html.DropDownListFor(m => m.WeatherLocation.LocationId, Model.Locations, "-Select a Location",
                new { @class = "form-control" })</div></div></div>

Model

public class WeatherVM
    {
       // public int LocationId { get; set; }
        public DateTime ForcastDate { get; set; }
        public WeatherLocation WeatherLocation;
        public IEnumerable<Weather> Weather { get; set; }
        public IEnumerable<SelectListItem> Locations { get; set; }

    }
}
public class WeatherLocation
    {
        [Key]
        public int LocationId { get; set; }
        [Required]
        public string LocationName { get; set; }
        [Required]
        public string Woeid { get; set; }
    }

Location table

id           Name    Woeid

1          EKM           asdsds

2         PPP              asdsad

I want to bring the dropdown in location please help

InvalidOperationException: The ViewData item that has the key 'WeatherLocation.LocationId' is of type 'System.Int32' but must be of type 'IEnumerable'.

$
0
0

Please help. When I am trying to poppulate the  data  in the same view ina table it always show the error InvalidOperationException: The ViewData item that has the key 'WeatherLocation.LocationId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'..

In Post method it shows the error 

InvalidOperationException: The ViewData item that has the key 'WeatherLocation.LocationId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
AspNetCore.Areas_Customer_Views_Forcast_Index.<ExecuteAsync>b__27_0() in Index.cshtml
+
@Html.DropDownListFor(m => m.WeatherLocation.LocationId, Model.Locations, "-Select a Location",

This error is coming when I poppulate the data on the table after I clicked the submit button and calling its post method. something error is coming in WeatherLocation please help

I am trying to list the record in the same view Index. It is working and the data is coming on the query but when I am trying to list the record on the index view  from post method , it is showing some error on the drop down of location . Please help

controller

 public async Task<IActionResult> Index()
        {
            IEnumerable<WeatherLocation> locList = _unitOfWork.Location.GetAll();
            ViewBag.LocationName = _unitOfWork.Location.GetAll();

            WeatherVM weatherVM = new WeatherVM()

            {

                Locations = locList.Select(i => new SelectListItem
                {
                    Text = i.LocationName,
                    Value = i.LocationId.ToString()
                }),
                WeatherLocation = new WeatherLocation()
            };

            weatherVM.ForcastDate= DateTime.UtcNow.Date;

            return View(weatherVM);
        }
        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Index(WeatherVM weatherVM)
        {
            IEnumerable<WeatherLocation> locList = _unitOfWork.Location.GetAll();
            int locationId = weatherVM.WeatherLocation.LocationId;
            var LocationObj = _unitOfWork.Location.
                        GetFirstOrDefault(l => l.LocationId == locationId);

            string _location = weatherVM.LocationName;
            string woied = LocationObj.Woeid;
            string forcastDate = weatherVM.ForcastDate.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
           // DateTime.Today.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
            if (_location == "B")
            {
                woied = "44544";
            }

            var weatherList = await _weatherRepository.GetWeatherAsync(woied,  forcastDate);
            
            weatherVM.Weather = weatherList;
            return View(weatherVM);
        }

View

@model MetaWeather.ViewModels.WeatherVM
@{
    ViewData["Title"] = "Index";
}<h1>Forcast Weather </h1><form asp-controller="Forcast" asp-action="Index" method="post"><div class="form-group"><div class="row"><div class="col-sm-2"><label asp-for="Locations">Locations</label></div><div class="col-4"><select class="form-control" asp-for="LocationName" data-role="select" selected="selected" data-parsley-errors-container="#errId17"><option value="">-- Select --</option><option value="B">Belfast</option><option value="L">London</option><option value="O">Other</option></select><span asp-validation-for="LocationName" class="text-danger"></span></div></div></div><div class="form-group"><div class="row"><div class="col-sm-2"><label asp-for="Locations">Locations</label></div><div class="col-4">
                @Html.DropDownListFor(m => m.WeatherLocation.LocationId, Model.Locations, "-Select a Location",
              new { @class = "form-control" })</div></div></div><div class="form-group row"><div class="col-sm-2"><label asp-for="ForcastDate"></label></div><div class="col-4"><input type='text' id="forcastDate" asp-for="ForcastDate" class="form-control" /><span asp-validation-for="ForcastDate" class="text-danger"></span></div><br /></div><div class="form-group row"><div class="col-4 offset-4"><button type="submit" class="btn btn-primary form-control">
                View</button></div></div><hr /><table>
        @if (Model.Weather == null)
        {<tr><td colspan="3" class="text-center">No Forcast Listed</td></tr>

        }
        else
        {
            <tr><th>ApplicableDate</th><th>WeatherStateName</th><th>WeatherStateAbbr</th><th>WindDirectionCompass</th><th>CreatedDate</th><th>MinTemp</th><th>MaxTemp</th><th>TheTemp</th><th>WindSpeed</th><th>windDirection</th><th>AirPressure</th><th>Humidity</th><th>Visibllity</th><th>Predictability</th><th></th></tr>
            @foreach (var item in Model.Weather)
            {<tr><td>@String.Format("{0:dd/MM/yyyy}", item.applicable_date)</td><td>@item.weather_state_name</td></tr>
            }
        }</table></form>
@section Scripts{<script>$(document).ready(function () {$("#forcastDate").datepicker({ format: 'dd/mm/yyyy', date: new Date(1900, 01, 01), autoclose: true, todayBtn: 'linked' });

        });
    </script>
}

Kept running into 401 unauthorize response using .NET Core v3.1

$
0
0

<div>I upgraded the source code to .NET Core v3.1 & I'm having trouble figuring how to debug the backend issue due to lot of dependency injections, abstractions & overriding classes/methods all over.  The employee who wrote this have overcomplicate things & he had left the company so we got stuck with the confusing source code mess here that take a lot of our time & energy, to make sense of the it.  :-/</div> <div> </div> <div>

The error I'm having is a 401 unauthorize response.  I discovered the debugger doesnt respond in StartUp class when consuming the webservice, it only respond when you start up the Web App.  So, it took us a while & finally found a hitting debugger breakpoint on a MVC controller page to point us in the right direction.  There it is saying the Identity is not authenticated so that explain the unauthorize error.</div> <div> </div> <div>

We're not familiar with this one authentication technology, `Odachi`.  We believe there are 2 seperate authentication architecture, which is ehe WebApp's webpages login authorization for the customer's web browser & Odachi deal with the WebApp's webservice login authorization for the 3rd party software making the webservice call.</div> <div> </div> <div>

Source code below is the webservice MVC controller w/ Authorization filter.   Then further down will be the Startup w/ base Startup abstraction.</div> <div></div> <div>

[ Webservice call ]</div> <div></div> <div>

namespace ABC.Payments.AspNet.MVC
{
    public class AuthorizeWithNoChallengeFilterAttribute : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.HttpContext.User?.Identity.IsAuthenticated != true)
                context.Result = new UnauthorizedResult();
            }
        }
    }

</div> <div></div> <div>

namespace ABC.Payments.MerchantWeb.Api
{
    [TypeFilter(typeof(AuthorizeWithNoChallengeFilterAttribute))]
    public class MerchantsV1Controller : Controller
    {
        [Route("api/v1/merchants/{merchantAccountId}/customers/payments/paymentmethods"), HttpPost]
        public async Task<ObjectResult> Payment([FromBody] ItemInfoViewModel itemInfo, CancellationToken cancellationToken)
        {
            var payments = whatever();
            return new HttpNotAcceptableObjectResult(payments);
        }
    }
}

</div> <div></div> <div>

[ Startup & Base Startup ]

</div> <div></div> <div> <div>

    namespace ABC.Payments.MerchantWeb</div> <div>   

{</div> <div>

        // StackOverflow Post on how to find 401 Unathorize error (debug)</div> <div> 

      // --> https://stackoverflow.com/questions/43574552/authorization-in-asp-net-core-always-401-unauthorized-for-authorize-attribute</div> <div> </div> <div>        public class Startup : StartupBase<MerchantRequestContext, Merchant></div> <div>

        {</div> <div>

            private const string _schemeCustomMerchantBasic = "CustomMerchantBasic";</div> <div> </div> <div>

            public Startup(IWebHostEnvironment webHostEnvironment)</div> <div>                : base(webHostEnvironment, PortalRoleType.Merchant)</div> <div>

            {</div> <div>

            }</div> <div> </div> <div>

            public void ConfigureServices(IServiceCollection services)</div> <div>

            {</div> <div>

                base._configureServices(true, services);</div> <div> </div> <div> 

              services.AddTransient(sp => sp.GetService<MerchantRequestContext>()?.Merchant);</div> <div>

                services.AddTransient(sp => sp.GetService<MerchantRequestContext>()?.Customer);</div> <div>

                services.AddTransient(sp => sp.GetService<MerchantRequestContext>()?.TenantSettings);</div> <div> </div> <div>

                services.AddLocalization(options =></div> <div>

                    {</div> <div> 

                      options.ResourcesPath = "Resources";</div> <div>

                    });</div> <div> 

              services.AddMvcCore()</div> <div>

                    .AddViewLocalization(LanguageViewLocationExpanderFormat.SubFolder, setup =></div> <div> 

                  {</div> <div>

                        setup.ResourcesPath = "Resources";</div> <div> 

                  })</div> <div> 

                  .AddDataAnnotationsLocalization()</div> <div> 

                  .AddApiExplorer();</div> <div> </div> <div>

                services.AddCors(options =></div> <div>

                    {</div> <div>

                        options.AddPolicy("Internal", p => p.WithOrigins(base._configuration["Cors:InternalSource"]).WithMethods("POST").WithHeaders("accept", "request", "authorization", "content-type", "internal"));</div> <div>

                    });</div> <div> </div> <div>

                services.AddAuthentication()</div> <div>

    // https://github.com/Kukkimonsuta/Odachi/blob/master/src/Odachi.AspNetCore.Authentication.Basic/Events/BasicSignInContext.cs  (Basic Sign Context)</div> <div>

    // https://github.com/Kukkimonsuta/Odachi/blob/master/samples/BasicAuthenticationSample/Startup.cs</div> <div>

                    .AddBasic(_schemeCustomMerchantBasic, options =></div> <div>

                    {</div> <div>

    //    ////////Notice: AutomaticChallenge is depreciated, google search said to use DefaultChallengeScheme w/ given cookie-authentication-scheme but that still doesnt explain how to disable it</div> <div>

    //    ////////        https://stackoverflow.com/questions/45878166/asp-net-core-2-0-disable-automatic-challenge</div> <div>

    //    ////////        https://github.com/dotnet/aspnetcore/issues/2007</div> <div> 

                      //## options.AutomaticChallenge = false;</div> <div>

                        options.Realm = "AutoPayment API v1";</div> <div>

                        options.Events = new BasicEvents()</div> <div>

                        {</div> <div>

                            OnSignIn = async context =></div> <div>

                            {</div> <div> 

                              var claims = new List<Claim>();</div> <div> </div> <div> 

                              if (context.Username == "ndi3DanDba993nvbaqbn3d93" && context.Password == "aVd3Ed51dfDE5acCCni9l1IxPq9")</div> <div> 

                                  claims.Add(new Claim(ClaimTypes.Role, "InternalAPIUser"));</div> <div> 

                              else</div> <div>

                                {</div> <div>

                                    string merchantAccountId = context.Request.Path.Value.Split('/').Skip(4).FirstOrDefault();</div> <div>

                                    var merchantRepository = context.HttpContext.RequestServices.GetRequiredService<IMerchantRepository>();</div> <div> </div> <div>   

                                if (merchantAccountId == null || merchantAccountId.Length != 14 || merchantAccountId.Split('-').Length != 3)</div> <div>

                                        throw new Exception($"Invalid merchant account Id ({merchantAccountId ?? string.Empty}).");</div> <div> </div> <div>

                                    var merchant = await merchantRepository.GetMerchantAsync(merchantAccountId, context.HttpContext.RequestAborted);</div> <div> 

                                  if (merchant == null || !merchant.IsActive || (merchant.GatePayApiKey != context.Username || merchant.GatePayApiSecret != context.Password))</div> <div> 

                                  {</div> <div>

                                        context.Fail("Invalid merchant"); //## context.HandleResponse();</div> <div> 

                                      return;</div> <div> 

                                  }</div> <div>

                                }</div> <div> </div> <div>

                                var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));  //## options.AuthenticationScheme));</div> <div> 

                              context.Principal = principal;</div> <div> </div> <div>

                                //## context.Ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), options.AuthenticationScheme);</div> <div>

                                context.Success(); //## context.HandleResponse();</div> <div>

                                //return Task.CompletedTask;</div> <div>

                            }</div> <div> 

                      };</div> <div>

                    });</div> <div> 

          }</div> <div> </div> <div>

            public void Configure(IApplicationBuilder applicationBuilder, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)</div> <div> 

          {</div> <div>

                base._configure(true, applicationBuilder, loggerFactory, serviceProvider);</div> <div> </div> <div> 

              applicationBuilder.UseCors("Internal");</div> <div> </div> <div> 

              applicationBuilder.UseWhen(context => !context.Request.Path.StartsWithSegments(new PathString("/api/v1")), b => b.UseAuthentication());</div> <div> 

          }</div> <div> 

      }</div> <div>

    }</div>

<div>    namespace ABC.Payments</div> <div>

    {</div> <div>

        public class StartupBase<TRequestContext, TUserContext> </div> <div>

            where TRequestContext : RequestContext<TUserContext></div> <div>

        {</div> <div>

            public StartupBase(IWebHostEnvironment webHostEnvironment, PortalRoleType portalRoleType)</div> <div>

            {</div> <div> 

              _portalRoleType = portalRoleType;</div> <div> 

              _webHostEnvironment = webHostEnvironment;</div> <div> </div> <div>

                var builder = new ConfigurationBuilder();</div> <div> 

              ConfigurationLoader.Load(builder, webHostEnvironment);</div> <div> 

              _configuration = builder.Build();</div> <div> </div> <div>

                if (webHostEnvironment.EnvironmentName.Equals("Production", StringComparison.OrdinalIgnoreCase) == true && _configuration["ConfirmProduction"]?.Equals("Yes", StringComparison.OrdinalIgnoreCase) != true)</div> <div>

                    throw new Exception("Azure defaults to \"Production\" for the environment, so you need to create an AppSetting of \"ConfirmProduction\" to \"Yes\" to ensure that is the intent.");</div> <div> 

          }</div> <div> </div> <div>

            private readonly IWebHostEnvironment _webHostEnvironment;</div> <div> 

          public readonly IConfiguration _configuration;</div> <div>

            private readonly PortalRoleType _portalRoleType;</div> <div> </div> <div>

            public void _configureServices(bool isWebBrowserFrontendGui, IServiceCollection services)</div> <div>

            {</div> <div>

                if (isWebBrowserFrontendGui)</div> <div> 

              {</div> <div>

                    services.AddDistributedRedisCache(options =></div> <div> 

                      {</div> <div>

                            options.Configuration = _configuration["Storage:Redis:Configuration"];</div> <div> 

                      });</div> <div> 

                  services.AddSingleton<RedisCache>();</div> <div> 

                  services.AddSingleton<MemoryDistributedCache>();</div> <div> 

                  services.AddSingleton<IDistributedCache>(</div> <div> 

                          sp => new ResilientDistributedCache(sp.GetRequiredService<RedisCache>(), sp.GetRequiredService<MemoryDistributedCache>())</div> <div> 

                      );</div> <div> </div> <div>

                    var azureBlobConnectionTring = _configuration["Storage:AzureBlob:ConnectionString"];</div> <div>

                    if (azureBlobConnectionTring != null)</div> <div>

                    {</div> <div>

                        var storageAccount = CloudStorageAccount.Parse(azureBlobConnectionTring);</div> <div>

                        var client = storageAccount.CreateCloudBlobClient();</div> <div> 

                      var azureBlobContainer = client.GetContainerReference("dataprotection-key-container");</div> <div> 

                      services.AddDataProtection().PersistKeysToAzureBlobStorage(azureBlobContainer, "keys.xml");</div> <div> 

                  }</div> <div> </div> <div> 

                  services.AddSession(options =></div> <div>

                    {</div> <div>

                        //options.IdleTimeout = TimeSpan.FromMinutes(5);</div> <div>

                    });</div> <div> </div> <div> 

                  services.AddDefaultIdentity<ApplicationUser>()</div> <div> 

                      .AddRoles<IdentityRole<Guid>>()</div> <div>

                        .AddEntityFrameworkStores<ApplicationContext>()  // FYI - AddEntityFrameworkStores() deal with role that derives from IdentityRole, as per documentation.</div> <div> 

                      .AddDefaultTokenProviders();</div> <div>

                    services.ConfigureApplicationCookie(options => {</div> <div> 

                      options.LoginPath = new PathString("/Home/Index");</div> <div>

                        options.SlidingExpiration = true;</div> <div>

                        options.ExpireTimeSpan = TimeSpan.FromMinutes(_configuration.GetValue<int?>("Authentication:SlidingExpirationTime").Value);</div> <div>

                        options.AccessDeniedPath = new PathString("/Home/AccessDenied");</div> <div> 

                  });</div> <div>

                    services.Configure<IdentityOptions>(options => {</div> <div> 

                      options.Password.RequireUppercase = false;</div> <div> 

                      options.Password.RequireLowercase = false;</div> <div>

                        options.Password.RequireNonAlphanumeric = false;</div> <div> 

                      options.Password.RequireDigit = false;</div> <div> 

                      options.Password.RequiredLength = 7;</div> <div>

                    });</div> <div> </div> <div> 

                  services.AddControllersWithViews();</div> <div> 

                  services.AddRazorPages();</div> <div> </div> <div> 

                  // AddMvc() vs AddMvcCore() explaination found at --> https://offering.solutions/blog/articles/2017/02/07/the-difference-between-addmvc-and-addmvccore/</div> <div>

                    //                                                --> https://stackoverflow.com/questions/42365275/how-to-implement-a-pure-asp-net-core-web-api-by-using-addmvccore/42365276#42365276</div> <div>

                   services.AddMvc().AddRazorRuntimeCompilation();</div> <div> </div> <div> 

                 services.Configure<MvcRazorRuntimeCompilationOptions>();</div> <div> 

                 services.Configure<AuthorizationOptions>(options =></div> <div> 

                 {</div> <div> 

                      options.DefaultPolicy = AuthorizationPolicy.Combine(options.DefaultPolicy,</div> <div> 

                          new AuthorizationPolicy(new IAuthorizationRequirement[] {</div> <div> 

                          new RolesAuthorizationRequirement(new string[] { _portalRoleType.ToString(), PortalRoleType.Internal.ToString() }),</div> <div>

                            new ImpersonationNotExpiredAuthorizationRequirement(_portalRoleType, _configuration.GetValue<TimeSpan?>("Authentication:ImpersonationTimeLimit").Value)</div> <div>

                            }, new string[0]));</div> <div> 

                  });</div> <div> </div> <div>   

                services.AddMvcCore(options =></div> <div>

                    {</div> <div>

                        var requestContextAttribute = new LoadRequestContextAttribute(typeof(TRequestContext));</div> <div> 

                      options.Filters.Add(requestContextAttribute); </div> <div> </div> <div> </div> <div> 

  options.ModelBinderProviders[options.ModelBinderProviders.IndexOf(</div> <div> </div> <div>

      options.ModelBinderProviders.OfType<ComplexTypeModelBinderProvider>().First()</div> <div> </div> <div> 

  )] = new TryServicesModelBinderProvider(services.BuildServiceProvider());</div> <div> 

                      options.ModelBinderProviders.Insert(0, new EnumModelBinderProvider(services.BuildServiceProvider()));</div> <div> 

                  })</div> <div> </div> <div> 

                  .AddDataAnnotationsLocalization()</div> <div> 

                  .AddNewtonsoftJson(settings =></div> <div> 

                  {</div> <div> 

                      settings.SerializerSettings.ContractResolver = new DefaultContractResolver();</div> <div> 

                  });</div> <div> </div> <div> 

                  services.Configure<ForwardedHeadersOptions>(options => options.RequireHeaderSymmetry = false);</div> <div>

                }</div> <div> </div> <div>

                //services.AddPayments<TRequestContext, TUserContext>(_configuration, string.Empty);</div> <div>

            }</div> <div> </div> <div> 

              public void _configure(bool isWebBrowserFrontendGui, IApplicationBuilder applicationBuilder, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)</div> <div> 

          {</div> <div>

               if (isWebBrowserFrontendGui)</div> <div> 

              {</div> <div> 

                  serviceProvider.GetRequiredService<ITelemeter<StartupBase>>().TrackMetric("Startup Time", (DateTime.UtcNow - DateTime.UtcNow).TotalSeconds);</div> <div> </div> <div> 

                  // Exception Page Handling.</div> <div>

                    if (!_webHostEnvironment.IsProduction())</div> <div> 

                  {</div> <div> 

                      applicationBuilder.UseDeveloperExceptionPage();</div> <div> 

                      //applicationBuilder.UseDatabaseErrorPage();</div> <div> 

                  }</div> <div> 

                  else</div> <div>

                        applicationBuilder.UseExceptionHandler("/Home/ErrorPage.html");</div> <div> </div> <div> 

                  applicationBuilder.UseStaticFiles(); // Note, we are not authenticating for static files if this is before them</div> <div>   

                //applicationBuilder.UseStatusCodePages();</div> <div> </div> <div> 

                  // Session.</div> <div> 

                  applicationBuilder.UseSession();</div> <div> </div> <div> 

                  applicationBuilder.UseAuthentication();</div> <div> </div> <div> 

                  // Routing.</div> <div> 

                  applicationBuilder.UseRouting();</div> <div> 

                  applicationBuilder.UseAuthorization();  // Exception error said to put this between UseRouting() & UseEnpoint().</div> <div> 

                  applicationBuilder.UseEndpoints(endpoints =></div> <div>

                    {</div> <div> 

                      endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");</div> <div>

                        endpoints.MapRazorPages();</div> <div> 

                  });</div> <div> </div> <div>

                    // Config Localization.</div> <div> 

                  var options = serviceProvider.GetService<IOptions<RequestLocalizationOptions>>();</div> <div> 

                  if (options != null)</div> <div> 

                      applicationBuilder.UseRequestLocalization(options.Value);</div> <div> </div> <div> 

                  applicationBuilder.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All });</div> <div> </div> <div> 

                  // Ensure Https.</div> <div> 

                  var portals = applicationBuilder.ApplicationServices.GetRequiredService<Portals>();</div> <div> 

                  applicationBuilder.Use(next => async httpContext =></div> <div> 

                  {</div> <div> 

                      if (httpContext.Request.Host.Value.Contains("localhost"))</div> <div>

                        {</div> <div> 

                          await next(httpContext);</div> <div> 

                      }</div> <div> 

                      else</div> <div> 

                      {</div> <div> 

                          string host = portals.GetHostForRedirect(httpContext.Request.Host.Value);</div> <div> 

                          if (!host.Equals((httpContext.Request.IsHttps ? "https://" : "http://") + httpContext.Request.Host, StringComparison.OrdinalIgnoreCase))</div> <div>         

                      httpContext.Response.Redirect($"{host}{httpContext.Request.Path}{httpContext.Request.QueryString}");</div> <div>

                            else</div> <div> 

                              await next(httpContext);</div> <div> 

                      }</div> <div> 

                  });</div> <div>   

            }</div> <div> </div> <div> 

              //applicationBuilder.UsePayments<TRequestContext, TUserContext>();</div> <div>

           }</div> <div> 

      }</div> <div> 

  }</div> <div></div> </div>

Viewing all 9386 articles
Browse latest View live


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