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

No connection could be made because the target machine actively refused it

$
0
0

Dear Friends,

I am facing issue again :(. I have deployed Web API and ASP.NET MVC CORE in dockers. MVC application is calling Web API using "HttpClient". However, I am getting following exception (It was working fine in development environment):

no connection could be made because the target machine actively refused it

Url for Web API: http://localhost:300/api/parser

Url for ASP.NET MVC:  http://localhost:301

I am able to telnet both ports. Firewall is also disabled. Any suggestion will be appreciated.

Thanks,

Pervaiz Khan.


Razor Pages: Best approach to redirection to areas

$
0
0

Hi all.

I'm developing a web applicaion using Razor Pages ans ASP.NET Core. I have different areas within my application for all the different modules of the page, but I would also like to have a "landing page" for each one, to make it easier for the user to remember the URL in case he wants to go directly. 

So, for instance, I have a page called Tracking (mysite.com/tracking), that when reached, redirects the user to the home page of thePackageTracking Area. To achieve this, I created a Tracking.cshtml Razor page in my root Pages folder, which in its OnGet method,redirects the user to the proper Area (PackageTracking/Index). But I'm thinking there might be a better approach to all this. Just having the Tracking.cshtml file means having a Razor page with no content, plus code behind code that just redirects.

Is there a better approach to this? I was thinking controllers and regular routing for my module "landing pages", but I'm not sure about mixing Razor Pages with a standard MVC approach.

Any ideas?

Thanks a lot.

Best practice to create Asp.Net Core project with database first and Individual identity

$
0
0

Greetings,

I am trying to create an Asp.Net Core project after building my db schema, also db first.

I make the reverse engineering part, generating the code files via Package manager console. I replace the context with the new one I create from the command.

But everytime I try to run the Update-Database command I get and error. The last error it gives me is "The entity type 'IdentityUserLogin<string>' requires a primary key to be defined.".

Can someone please help me solve this and tell me a best practice how to work with db first and use asp.net identity with individual account too, to add all the required tables for it in the already existing db. Also if possible, to show how to update the models when I make changes on the db, also best possible and shortest way, without breaking too much code.

Thank you in advance.

search for Identity user by their fields in .net core

$
0
0

public class ApplicationUser : IdentityUser
{
public Boolean status { get; set; }
}

var result1 = _context.Users.Where(x => x.Email == model.Email && x.status == true).FirstOrDefaultAsync();

does not work. It is not related to signin or login. 

How to set focus on a control after post back call in asp.net core razor page

$
0
0

Hi, am calling a Post method of my page model on button click using "asp-page-handler", after execution am returning the page(return Page()) which reloads the page and the focus is automatically set to top of the page.Here I want to set focus to button I clicked. Is there any possibilities to do this. Thanks in advance

Interface and async

$
0
0

Not really sure how to ask this...

I have the following interface:

 public interface IFish
    {
        IEnumerable<Fish> GetAll();

        IEnumerable<Fish> GetAllFishWithVendor();

        //IQueryable GetAll(); // more performant on large data sets
        Fish Get(int id);

        Fish Add(Fish newFish);

        Fish Update(Fish fish);
    }

and the following implementer:

 public class SqlFishData : IFish
    {
        private FishRoomDbContext _context;

        public SqlFishData(FishRoomDbContext context)
        {
            _context = context;
        }

        public Fish Add(Fish newFish)
        {
            _context.Fishes.Add(newFish);
            _context.SaveChanges();
            return newFish;
        }

        public Fish Get(int id)
        {
            return _context.Fishes.FirstOrDefault(f => f.Id == id);
        }

        public IEnumerable<Fish> GetAll()
        {
            return _context.Fishes.OrderBy(f => f.Name);
        }

        public IEnumerable<Fish> GetAllFishWithVendor()
        {
            // return all corals and vendor
            return _context.Fishes.Include(f => f.Vendor).OrderBy(c => c.Name);
        }

        public Fish Update(Fish fish)
        {
            _context.Attach(fish).State = EntityState.Modified;
            _context.SaveChanges();
            return fish;
        }
    }

This is how I'm calling in my Razor Page:

        public void OnGet()
        {
            //using interface
            Fish = _fish.GetAllFishWithVendor().ToList();
        }

My question is how can I call this async?  

Thanks!

Autologin using Windows Authentication & ASP.NET Core 2

$
0
0

Hello,

I have an application written in ASP.NET Core 2 that uses Windows authentication: for now, when a user (previously connected to the PC and the domain) opens the browser (IE),  the login form is opened, asking for the user and password; typing the correct credentials the user accesses the application,  but I would like it to be an "automatic login", without re-typing the user and password; my impression is that the configuration of the identity of the application pool associated with the site is wrong: what kind of privileges should this user or group have? Do you have any suggestions for checking it?

Any help is appreciated

ASP.net Core ViewComponent validate model on http post

$
0
0

I created a view component that contains a form with user inputs fields like textbox, dropdown ...etc. I tried to leave a required input field empty when I submitted the form. I got the correct result with error on required field validation and the textbox field did not render the old value it just return empty with required massage. 

also I tried to validate expression on comparing two fields and I got a correct message that two input fields are not the same.

the question is: 

How on post and submitting the form the model did not repopulate the old values. even in the component action I am repopulating the data.

does view component preserve user input if model is not valid?

   public IViewComponentResult Invoke(NavigationDestination navigationDestination)
        {
            var model = new IncomeViewModel();

             // Code to Build the model

            return View(model);
        }


Correct way to map tables using the EF?

$
0
0

Hello,

i'm a junior dev working on my first, big, .NET Core project.

I have a doubt about the Entity Framework and how to map the tables in my db to my models, from what i understood, there are 2 ways:

  1. My models' proprieties, having the same name as the table columns will map them automatically
  2. Proprieties declaration inside the OnModelCreating method inside DbContext class

From https://docs.microsoft.com/en-us/ef/core/modeling/relational/columns

By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreatingmethod are also included. Finally, any types that are found by recursively exploring the navigation properties of discovered types are also included in the model.

An example of 1.

public class Event
{
   [Required]
   public string Title { get; set; }
}

An example of 2.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Event>(entity =>
{
entity.Property(e => e.title).hascolumnname("title").isrequired(); }
}

How to get records from multiple table in linq

$
0
0

I have 5 tables Workflow as 'A',WorkflowSteps as 'B',AppUser as 'C' ,AppRoles as 'D' and AppDepartment as 'E' I want to get the record in the way that the

1) matching records from A and B based on workflowId 

2) matching Records From B and C, B and D, B and E because table B have foreign keys UserId, RoleId and DepartmentId

but the problem is for some column in B UserId is null some have DepartmentId as Null and some have RoleId is Null so inner join won't work

here is my query it will have to fetch three rows but i am getting 0

var workflows = (from q in _context.WorkFlowSteps
                             join p in _context.WorkFlow
                             on q.WorkFlowId equals p.WorkFlowId
                             join r in _context.AppUsers
                             on q.ApprovalUserId equals r.UserId
                             from dep in _context.AppDepartment
                             from role in _context.AppRoles
                             where (q.DepartmentId == dep.DepartmentId) && (q.RoleId == role.RoleId)&& (q.WorkFlowId == id && q.IsAllowed == true && p.WebSiteId == WebsiteId)
                             select new WorkFlowViewModel
                             {
                                 UserId =Convert.ToInt32(q.ApprovalUserId.HasValue?q.ApprovalUserId:(q.DepartmentId.HasValue?q.DepartmentId:q.RoleId)),
                                 ModeId = p.ModeId,
                                 WebSiteId = p.WebSiteId,
                                 Step = q.StepNo,
                                 Name =q.ApprovalUserId.HasValue? p.Name :(q.DepartmentId.HasValue? dep.Name :r.Name),
                                 WorkFlowId = p.WorkFlowId
                             }).ToList();

Sendgrid with .Net Core 2.1

$
0
0

Hi Friends,

Does anyone know where I can find a good detailed tutorial on how to use the send grid API with the registration component of my
application. I always find the tutorials very incomplete in explaining how to use send grid. I have tried every version ofasp.net and can't get 
it to work. Thanks !

How to increase upload file size in ASP.Net Core

$
0
0

I am using ASP.Net Core with MVC6. I need to upload file size 20 MB or more.

Thanks

Asp Core InProc Session use without serialization

$
0
0

(apologies for posting this here and on stack overflow, I don't know which is the best practical avenue for getting a response)

Is there anyway of using InProc session in Asp.Net Core with having to serialize the data each time? We have an website that's 15+ years old, it uses a lot of Session up to and including storing DataSets in the session. Serializing the data on every call is (probably) going to be a big hit.

I'm aware that InProc session can be lost at any point and you wouldn't architect a modern website this way, but this is the only issue that's stopping us migrating to Core (we've already done the handlers and modules)

How to retain the list binded with Select control after a postback call using asp-page-handler

$
0
0

I have a Select  control in my page and its is mapped with a list property in the PageModel . When am doing a post call using asp-page-handler PageModel list values  is getting cleared and I have to do a DataBase call  on that Post Method (called by the asp-page-handler) to reload the PageModel property. I tried with putting the list values in TempData and it works with smaller list data, if List data is huge then its throws an error. Is there any other possibility to retain the list. Below is the sample code I tried

Razor Page:

<select  asp-for="MyModel.Emp"  asp-items=" Model.EmpList.Select( m => new SelectListItem { Text= m.Name, Value = m.ID})"></select>

PageModel:

[BindProperty]
public List<Employee> EmpList{ get; set; }

Client side validation not working in bootstrap modal on a partail vew

$
0
0

Hi,

I can't make the client validation work on a modal form, the modal doesn't show the validation messages and never close even if I redirect after successfull save.

Here's the Controller function that saves the infos.

 public IActionResult CompleteReg(UserViewModel model)
        {

            if (ModelState.IsValid)
            {
                
                return RedirectToAction("UserHome");
            }
            else
            {
                return PartialView("_ConfirmReg",model);
            }

          
        }

Here's part off the View containing the partial view:

<form asp-action="CompleteReg" asp-controller="User" method="post" data-ajax="true" data-ajax-update="frmConfirm"><div class="modal fade" id="CompleteReg" tabindex="-1" role="dialog" aria-labelledby="CompleteReg" aria-hidden="true"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="exampleModalLabel">Complétez votre profil</h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button></div><div class="modal-body" id="frmConfirm">
                    @await Html.PartialAsync("_ConfirmReg")</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button><button type="submit" class="btn btn-primary">Sauvegarder</button></div></div></div></div></form>



@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

And the partial view:

@using Commun_PLSD
@using Microsoft.AspNetCore.Mvc.Localization
@using PLSD.Models.HomeViewModels

@model UserViewModel

<input type="hidden" asp-for="UserID" /><div class="form-group row"><label asp-for="DonorNumber" class="col-4 col-form-label"></label><div class="col-8"><input asp-for="DonorNumber" class="form-control" /><span asp-validation-for="DonorNumber" class="text-danger"></span></div></div><div class="form-group row"><label asp-for="BirthDate" class="col-4 col-form-label"></label><div class="col-8"><input asp-for="BirthDate" class="form-control" placeholder="jj-mm-yyyy" /><span asp-validation-for="BirthDate" class="text-danger"></span></div></div><div class="form-group row"><label asp-for="PostalCode" class="col-4 col-form-label"></label><div class="col-8"><input asp-for="PostalCode" class="form-control" placeholder="A9A 9A9" /><span asp-validation-for="PostalCode" class="text-danger"></span></div></div>


@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

And the model:

public class UserViewModel
    {
        public List<Centre> Centers { get; set; }
        public string Name { get; set; }
        public string FirstName { get; set; }
        public string FullName
        {
            get
            {
                return FirstName + " " + Name;
            }
        }

        public bool OpenModal { get; set; }

        [Required(ErrorMessage ="Le {0} est obligatoire")]
        [StringLength(7, ErrorMessage = "Le {0} doit avoir au moins {2} et un maximun de {1} caractères.", MinimumLength = 2)]
        [Display(Name = "Numéro de donneur")]
        public string DonorNumber { get; set; }

        [Required(ErrorMessage = "Le {0} est obligatoire")]
        [DateFormatValidator(ErrorMessage = "Format de date non valide")]
        [Display(Name = "Date de naisance")]
        public string BirthDate { get; set; }

        [Required(ErrorMessage = "Le {0} est obligatoire")]
        [StringLength(7, ErrorMessage = "Le {0} doit être composé de 7 caractères.", MinimumLength = 7)]
        [Display(Name = "Code postal")]
        public string PostalCode { get; set; }

        public string UserID { get; set; }
        public StatutCompteLocal Statut { get; set; }

        public List<DisplayMessage> Messages { get; set; }

    }

I used to do this in standard ASP.Net MVC with no problems!


Problem on configuring Entity framework and appsetting

$
0
0

Hi

I'm trying to learn asp core from tutorialspoint.com but it seems this tutorial is for previous version of this framework and I can't configure appsetting.json and entity framework and vs doesn't accept them:

here comes my code for configuring appsetting.json:

public class Startup { 
      public Startup() { 
         var builder = new ConfigurationBuilder()   
            .AddJsonFile("AppSettings.json"); 
         Configuration = builder.Build(); 
      }

here comes my code for configuring entity framework:

public void ConfigureServices(IServiceCollection services) { 
   services.AddMvc(); 
   services.AddEntityFramework() 
      .AddSqlServer() 
      .AddDbContext<FirstAppDemoDbContext>
   (option => option.UseSqlServer(Configuration["database:connection"])); 
} 

Which items should be changed? Please inform me.

thanks

Saeed

Asp.net (MVC)Core 2.1 version Jquery Data table plugin issue

$
0
0

I am trying to use jquery.dataTables.min.js in my asp.net mvc core 2.1 version. Though i have included all scripts in correct order i am getting the error saying "uncaught typeerror $(...).datatable is not a function".

<linkhref="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css"rel="stylesheet"/><linkhref="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css"rel="stylesheet"/><scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><scriptsrc="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script><scriptsrc="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script><divclass="container"><br/><divstyle="width:90%;margin:0 auto;"><tableid="example"class="table table-striped table-bordered dt-responsive nowrap"width="100%"cellspacing="0"><thead><tr><th>CustomerID</th><th>Name</th></tr></thead></table></div></div><script>$(document).ready(function(){$("#example").DataTable({"processing":true,// for show progress bar"serverSide":true,// for process server side"filter":true,// this is for disable filter (search box)"orderMulti":false,// for disable multiple column at once"ajax":{"url":"https://data.sfgov.org/resource/RowID.json","type":"GET","datatype":"json"},"columnDefs":[{"targets":[0],"visible":false,"searchable":false}],"columns":[{"data":"number_of_alarms","name":"number_of_alarms","autoWidth":true},{"data":"on_scene_dttm","name":"on_scene_dttm","autoWidth":true},]});});</script>

Dotnet CLI builds much slower than VS2017

$
0
0

I have an ASP Core 2.0 project that builds via VS2017 (community) in 2.5 minutes. When I build with dotnet (same machine) it takes 8.5 minutes.

I see similar issues with other projects as well. When I first started investigating this the ASP project took 20+ minutes to build. I discovered that Windows Defender was the culprit there. I added some exceptions (for Nuget and project file locations) and that lowered the time to 8+ minutes.

I am at a loss as to why there is such a difference between VS and CLI.

Machine is a MacBook Pro, I7, 16GB RAM running Windows 10 Pro via Bootcamp. It is a dev box so installed software is mostly tools (VS, Code, Sublime, Postman, Fiddler).

Taskman is not showing anything mysterious running or consuming resources.

If anyone can shed any light on this it would be appreciated.

Role based authorization with Windows Authentication

$
0
0

I am working on an MVC Core application where i have enabled Windows Authentication. It is working fine. Now i have to add a layer of Role-based Authorization to it. Can someone help me how can i proceed with that? I need to maintain roles in my application, need to provide screens for the user with admin role to be able to manage roles for other users. Please point me to correct approach of implementing it

Ocelot API Gateway using .Net Core 2.1

$
0
0

Hi All,

I'm new to API Gateway and follow the below link to start with.

    https://www.c-sharpcorner.com/article/building-api-gateway-using-ocelot-in-asp-net-core/

I have created two APIs Customers and Products with two different ports which are tested and working fine.

I've created an API gateway using Ocelot in AP.Net CORE 2.1 and when I try to execute with another port (http://localhost:9000/api/products), it throws an error as shown below. I use IIS Express.

                       HTTP Error 502.3 - Bad Gateway

                          There was a connection error while trying to route the request.

Here are the code snippets:

Program.cs

namespace APIGateway
{
public class Program
{
public static void Main(string[] args)
{
IWebHostBuilder builder = new WebHostBuilder();
builder.ConfigureServices(s =>
{
s.AddSingleton(builder);
});
builder.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
// Replaces call to UseIISPlatformHandlerUrl()
//.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://localhost:9000");

IWebHost host = builder.Build();
host.Run();
}
}
}

Startup.cs

namespace APIGateway
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
builder.SetBasePath(env.ContentRootPath)
//add configuration.json
.AddJsonFile("configuration.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();

Configuration = builder.Build();
}

//change
public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
Action<ConfigurationBuilderCachePart> settings = (x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);

}).WithDictionaryHandle();
};
//services.AddOcelot(Configuration, settings);
services.AddOcelot(Configuration);
}

//don't use Task here
public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
await app.UseOcelot();
}
}
}

Configuration.json

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/customers",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9001
}
],
"UpstreamPathTemplate": "/customers",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/customers/{id}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9001
}
],
"UpstreamPathTemplate": "/customers/{id}",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9002
}
],
"UpstreamPathTemplate": "/api/products",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"RequestIdKey": "OcRequestId",
"AdministrationPath": "/administration"
}
}

launchSettings.cs

{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:9000",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"APIGateway": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"

}
}
}

Thanks,

Anand

Viewing all 9386 articles
Browse latest View live