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

If you connect two libraries, then debugging does not work?

$
0
0

I add two class libraries to the "solution".
I am running debugging.
Chrome starts up.
In Chrome, the start page `\Home\Index.cshtml` appears.
After `~10` seconds, debugging automatically stops.

Description.
I created a project - `WebApplCore`;
I added a class library to the solution - `Models`;
I added a class library to the solution - `DBRepository`.

Project `WebApplCore` - ASP.NET Core;
Class Library `Models`, `DBRepository` - Net.Standard 2.0.

Conditional notations for "tests": 
- "+" - `project` is included in the `decision`;
- "-" - `project` is not included in the `decision`.


Test 1.
WebApplCore - "+";
Models - "+";
DBRepository - "-".
Result: debugging works stably. Turning off debugging does not occur.


Test 2.
WebApplCore - "+";
Models - "-";
DBRepository - "+".
Result: debugging works stably. Turning off debugging does not occur.

Test 3. !!!
WebApplCore - "+";
Models - "+";
DBRepository - "+".
Result: debugging does not work stably !!!. After ~10 seconds, debugging automatically stops.

Question.
Why in **Test 3.!!!** does debugging turn off?

Picture-1



Picture-2



Picture-3 


Picture-4


Picture-5




Swagger Page Doesn't Display Example Schema

$
0
0

Hello,

I am having Asp.Net 3.1 application where I use swagger UI to display the API documentation but In my case previously I was using [DataMember] Attribute for the properties and in that case example schema were displayed in the documentation but when I use System.text.json.Serializatio which is provided as default by .Net Core 3.1 In that case Exaample schema in the documentation looks like this'{}'. What Else to be done in this case ?

services.AddSwaggerGen(confiuration);
services.AddSwaggerGenNewtonsoftSupport();

Deploy ASP.NET CORE IN TO IIS

$
0
0

Hi,

Do we need really need to include following code in Program.cs .

.UseIISIntegration(),

.UseKestrel()

For deploying Asp.net core application in to IIS.

Regards,

krrish

NotFound Page in Asp.net Core

$
0
0

Hi,

i want design 404 page in my project and i have use culture root ,

my startup

 app.Use(async (context, next) =>
            {
                await next();
                if (context.Response.StatusCode == 404)
                {
                    context.Request.Path = "fa/error_404";
                    await next();
                }
            });

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                endpoints.MapControllerRoute(
                name: "areas",
                pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

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



            });
 [Route("/error_404")]
        [Route("{culture}/error_404")]
        public async Task<IActionResult> AboutUs()
        {           
            return View();
        }

my default url is /fa

but when i search a not exsits url for example  /fa/Jfejsfd    its not got error_404 action and return not found




How to Use WIX installer with net core Web app?

$
0
0

Hello all,

I want to use WIX installer with Dot Net Core Application along with that I want to integrate IIS hosting and SQL express in wix installer with net core web application.
Currently I have implemented WIX installer with windows application and I need help how to implement IIS express and SQL express with wix installer and dot net core application.

Please suggest me some solution or give some reference for same.

Thanking you.

cycles or multiple cascade paths in ef core

$
0
0

Hi,

i have this error in update database , whats problem ?

ProductInfo.cs

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

  [InverseProperty("ProductInfo")]
        public virtual IEnumerable<SimilarProduct> SimilarProduct { get; set; }


        [InverseProperty("SimilarProduct1")]
        public virtual IEnumerable<SimilarProduct> SimilarProduct2 { get; set; }

SimilarProduct.cs

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

        [ForeignKey("ProductInfo")]
        public int ProductInfo_ID { get; set; }
        public ProductInfo ProductInfo { get; set; }


        [ForeignKey("SimilarProduct1")]
        public int ProductSimilarID { get; set; }
        public ProductInfo SimilarProduct1 { get; set; }

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

i set this but its not worked 

          builder.Entity<SimilarProduct>()       // THIS IS FIRST
.HasOne(u => u.ProductInfo).WithMany(u => u.SimilarProduct).IsRequired().OnDelete(DeleteBehavior.Restrict);

            builder.Entity<SimilarProduct>()
       .HasOne(pt => pt.SimilarProduct1)
       .WithMany(p => p.SimilarProduct2)
       .HasForeignKey(pt => pt.ProductSimilarID).OnDelete(DeleteBehavior.Restrict); 



Dynamically adding/removing HTML table entries

$
0
0

I am developing a SPA using ASP.NET Core 3.1 Razor.

In one of the Create Model screens, I have a nested collection E.g "Create Customer" screen has to allow the user to add a collection of his/her Cars in this screen.

I have seen examples of dynamically adding HTML table rows but it doesn't seem to work in Razor SPA. Please help with any examples.

Missing optional routing argument not null

$
0
0

Hi!

I have a simple route with an optional "version" argument:

routes.MapRoute(name: "pages", template: "{action=Index}/{version?}", defaults: new { Controller = "Pages" });

and corresponding action method:

public IActionResult Index(Version version = null) { ... }

However, when I navigate to / the action method gets invoked with version = 0.0, not null. Where does that value come from and how can I fix that?

Thanks!


where to find trirand web.ui.controls

Spike in CPU usage.

$
0
0

Hello,

I am using ASP.NET Core 2.2. We are facing an issue from the last few days that there is sudden spike in CPU usage of my application after 8-10 hours. Then the system is required to be restarted and everything is back normal again. 

I have tried profiling the code but is not able to figure out the issue. What is the common way through which I can identify the issue or what should be the best practices in order to avoid such scenarios? Basically I have 5 background services running infinitely with a delay of 2-5 minutes which syncs Mailboxes via Gmail, Outlook API and IMAP using Mimekit.

Thanks

Dynamic web application with ASP.NET core

$
0
0

Hi, I want to add a dynamic page loading feature to my website, basically I want to load more content on my website page when someone reaches the end or when user presses the load more button. for eg check this link and scroll to the bottom of the page u will see the content will dynamically load-https://dribbble.com/. So can you tell me if I should make dynamic loading pages with signalR or I should use something else for it and if no what should I use and if I can use SignalR will it how much server heavy it is???

Fault Tolerant Background Job

$
0
0

I have a service worker up and running in my ASP.NET Core 2.2 app. I am exposed to a problem that I want to solve which is to create a fault-tolerant background service. 

I have a shared table on which two different jobs select and update data. Basically what we are doing is that we are syncing Office Calendar and Mail so the token has to be stored in the database. If any of the services fails to access the API they refresh access by using refresh token and then updates it in the database as well. Now there might be a situation that one of the services is working on the same row while other has updated the tokens in the database and we might end up in an infinite loop and both update the tokens over and over again. What should be the workaround to avoid such scenarios?

Thanks

asp.net core static file caching doesn't work

$
0
0

I am using the Angular project template with ASP.NET Core. Reference

The caching should be enabled by default, to be sure I have added an StaticFileOptions object to the StaticfileMiddleware:

public class Startup
{
 // ...
 app.UseStaticFiles(new StaticFileOptions
 {
     OnPrepareResponse = ctx =>
         {
             const int durationInSeconds = 60 * 60 * 24;
             ctx.Context.Response.Headers[HeaderNames.CacheControl] ="public,max-age=" + durationInSeconds;
         }
 });
 // ...
}

Then I have created an test.html in wwwroot folder.

<!DOCTYPE html><html lang="en"><head><meta charset=utf-8><title>Test static files</title></head><body>
    This is a test for static files!</body></html>

When I dotnet run and navigate to https://localhost:5001/test.html the page is displayed correctly.

test.html

After I change the html page, I click to google chrome's address bar and press enter, to issue another HTTP request to the test.html file. I have not reload the page.

test.html after change

You can see that the change is reflected by google chrome and I received an status 200 again instead of 304. Cache-control in the Response Header is public,max-age=86400. Why does the static file caching not work? My desired result would be that the change is not reflected after the second HTTP request, so I can be sure static file caching is working properly.

I am using: .NET Core SDK 3.1.201 and Chrome 80.0.3987.163.

RedirectToPage() not working from AJAX handler

$
0
0

I'm using Razor Pages and have a handler called OnPostDeleteAsync(). The handler is working but, after the item is deleted, I want to refresh the page.

I could refresh the page from my JavaScript code but would do it from my server-side handler if possible.

I've seen a lot of code examples that seem to do this using return RedirectToPage(). But I cannot get this to work from my AJAX handler. It just works normally, no error, but there is no page refresh or redirect.

Does anyone know why this might not work?

Page Routing based on a custom value

$
0
0

Hello:

I need to authorize MVC pages based on a combination of custom values that I obtain from the user logged in, for example:

A logged in user will see a certain page(s) if they have a code value of "ABCD" that I generate from querying certain values from their extension attributes. If the code value is "WXYZ" then they will see another page.

Thanks.


Type or namespace error in startup.cs doesnt make sense

$
0
0

I have a Net Core 3.1.1 (Blazor) app that i have generated a "reverse engineer" configuration via EntityFramework PowerTools  for. This generates dbcontext and allows me to assign tables from my dbase into the model. I have done this correctly with another project, but the project I am now trying this with is giving me "Type or namespace .." error in startup.cs 

Efpt.configu json (partial)

{
"ContextClassName": "MyDatabaseContext",
"ContextNamespace": null,
"DefaultDacpacSchema": null,
"DoNotCombineNamespace": false,
"IdReplace": false,
"IncludeConnectionString": false,
"ModelNamespace": null,
"OutputContextPath": null,
"OutputPath": "Data\\MyProject",
"ProjectRootNamespace": "MyProjectDB",
"SelectedHandlebarsLanguage": 0,
"SelectedToBeGenerated": 0,
"Tables": [
{
"HasPrimaryKey": true,
"Name": "[dbo].[MyTable]"
}
],
....

my startup.cs for the ConfigureServices method, with using headers for startup.cs:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MyProject.Areas.Identity;
using MyProject.Data;


namespace MyProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}


public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
// Read the connection string from the appsettings.json file
// Set the database connection for the MyDatabaseContext

services.AddDbContext<MyProjectDB.Data.MyProjectDB.MyProjectDBContext>
.....

..whereas MyProjectDB inside this last line for the list type is where the error is pointing, but i do have MyProjectDB assigned inside efpt.config.json as the projectname rootspace 

??
thanks in advance
Ned



pulling a numerical value out of a dropdown box html

$
0
0

Looking for some help on how to pull out a numerical value from a drop down box back into an if statement in a  controller:

Dropdown box:

<div class="form-group"><select class="form-control" name="Role"><option value="">Select your accout type</option><option value="0">optionOne</option><option value="1">otionTwo</option></select></div>
 if (optionOne)
 {
       Users.Role = 2;                
 }

 if(optionTwo)                
 { 
       Users.Role = 3;
 }




Dependency injection in HostedService failing

$
0
0

Hi,

I am busy on a asp net core application where I need to perform a background task on my database once a day. So reading https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio I made a background service that's working fine.  But in order to do something with it I need to access my database with the database context.  I wanted to use Dependency injection like I do with all my other classes. But then I get a runtime error : HTTP Error 500.30 ANCM In-Process start failure.

The relevant code:

 public class BackgroundService : IHostedService, IDisposable
    {
        private readonly Data.ApplicationDbContext _DB;
        private int executionCount = 0;
        private readonly ILogger<BackgroundService> _logger;

        private Timer _timer;

        //public BackgroundService(Data.ApplicationDbContext DB, ILogger<BackgroundService> logger) //this fails!!
        public BackgroundService( ILogger<BackgroundService> logger)  //This works
        {
            _logger = logger;
           // _DB = DB;
        }
....

Can somebody tell me what I do wrong? 

thanks i advance.

Rob

My MVC Core new website is showing Directory lIsting

$
0
0

I am new to Asp net core. I Made new web Site in MVC Core , Created an instance of EC2,Configured IIS in it then i Created a new website and deployed the application there . It  is showing directory listing there.Ran aspnet_regiis -i command in version folder , Still it is not working. Please help me to fix this problem

How to sanitize inputs for Html.Raw on server side

$
0
0

I have several views where I use @Html.Raw and would like to sanitize rich text inputs. Possibly what the Rich Text Box may emit and take a white list type of approach to the tags/attributes that the server-side will accept. I'm not sure how to do this or where to look to do this.

                            @foreach (var dorItem in catGroup)
                            {<tr><td class="view-dor">@Html.Raw(dorItem.Responsibility)</td><td class="view-dor-description">@Html.Raw(dorItem.Description)<div class="verticalspace"></div>
                                        @foreach (var dorResponse in dorItem.DorItemResponses)
                                        {<div style=" border: solid black 1px; background-color: #eeeeee;"><b>@dorResponse.Date.ToString("MM/dd/yyyy") @dorResponse.Title</b><div class="verticalspace"></div>@Html.Raw(dorResponse.Response)</div>
                                        }</td>
                                    @if (@dorItem.Status.Color.Name == "Yellow")
                                    {<td class="view-dor"><font class="dor-status-dark"
                                                  color="@dorItem.Status.Color.Name"><b>@dorItem.Status.Name</b></font></td>
                                        }
                                        else
                                        {<td class="view-dor"><font color="@dorItem.Status.Color.Name"><b>@dorItem.Status.Name</b></font></td>
                                        }</tr>
                            }

Viewing all 9386 articles
Browse latest View live