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

How to Add Trusted Issuer for .net core application.

$
0
0

Hi,

I am using WSFederation for authenticating the users in .Net Core Application.  There is an STS service which will authenticate and supply claims for me. I have added the required Metadata address and the WRealm are provided. This is working fine on the local machine but stopped working after deployment to the Server using VSTS build. The error it is throwing is 

"Peer certificate cannot be authenticated with given CA certificates". 

After enquiring about this the admin team they said that we need to add the STS server certificate thumbprint to my application as part of the deployment. I searched for adding thumbprint in google but no luck. 

Please let me know how can I add a thumbprint of the trusted issuer in.Net Core Application. We would do in the Web.Config for Dot Net Framework application. I want to do the same in my Dot Net Core application.


Apply downloaded theme to .Net core project

$
0
0

Can someone tell me? how to apply the all.css and variables.scss files downloaded from the SASS Themebuilder to my .Net Core project?

Thanks.

I want the working combination of jquery, jmoment, jbootstrap, jbootstrap datetimepicker

$
0
0

in .net core app jquery2.2.0min, bootstrap 3.3.7min was in working condition.

To use bootstrap datetimepicker 4.17.45, i had to upgrade. Now all versions got

tangled and latest jquery3.3.7 is not working for me. I want the working combination of jquery, jmoment, jbootstrap, jbootstrap datetimepicker. Please help.

Cannot restore references in project! .NET Core

$
0
0

Could someone take a look at screenshot about asp.net core errors in project. If there is some solution to fix this error please share! Markus..

https://imgur.com/a/XtLQr6R

How to specify Etag or Last-Modified header for images that ImageSharp Generates (Crop & Resized)

$
0
0

Hello.

I am using ImageSharp for crop and resize on the fly in ASP.NET Core.

I have an API :

[HttpGet("/image/{width:int:min(0)}/{height:int:min(0)}/{*url}")]
        public async Task<IActionResult> ResizeImage(string url, int width, int height)
        {
            if (width < 0 || height < 0 ) { return BadRequest(); }
            if (width == 0 && height == 0) { return BadRequest(); }

            var key = $"/{width}/{height}/{url}";
            var data = await _cache.GetAsync(key);
            if (data == null)
            {
                var imagePath = PathString.FromUriComponent("/" + url);  
                var fileInfo = _fileProvider.GetFileInfo(imagePath);  
                if (!fileInfo.Exists) { return NotFound(); }

                data = ips.CropResize(fileInfo,height,width);

                const int durationInSeconds = 60 * 60 * 24 * 7;
                ctx.HttpContext.Response.Headers[HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
                var cacheEntryOptions = new DistributedCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromHours(7));
                await _cache.SetAsync(key, data,cacheEntryOptions); 
            }

and i have a CropResiz method :

public byte[] CropResize(IFileInfo fileInfo,int height,int width)
        {
            using (var outputStream = new MemoryStream())  
            {
                using (var inputStream = fileInfo.CreateReadStream())
                {
                    using (var image = Image.Load(inputStream))
                    {
                        var currentW = image.Width;
                        var currentH = image.Height;
                        if(currentW > currentH)
                        {
                            image
                            .Resize(0,height);
                            var resizedW = image.Width;
                            var cropX = (resizedW / 2) - (width / 2);
                            var resizedH = image.Height;
                            var cropY = (resizedH / 2) - (height / 2);

                            image
                            .Crop(new Rectangle(cropX, cropY, width, height))
                            .SaveAsJpeg(outputStream,new JpegEncoder(){Quality = 80});
                        }
                        else
                        {
                            
                            image
                            .Resize(width,0);

                            var resizedW = image.Width;
                            var cropX = (resizedW / 2) - (width / 2);
                            var resizedH = image.Height;
                            var cropY = (resizedH / 2) - (height / 2);

                            image
                            .Crop(new Rectangle(cropX, cropY, width, height))
                            .SaveAsJpeg(outputStream,new JpegEncoder(){Quality = 80});
                        }
                    }
                }

                return outputStream.ToArray();
            }
        }

Now it works fine, but the problem is when i check my website in GTmetrix.com i get Specify a cache validator error for this images.

Exactly images that i request by ImageSharp api.

Anybody can help me to know how can i specify cache validator to this images?

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

Updating textarea when event fires in code behind

$
0
0

I'm writing a multi platform app to connect to a build service running on a separate machine. The build service starts when it receives a TCP/IP message from my app. As the build is happening, the build service sends the build output back to my app via TCP/IP.

My app is a shared project (Windows, Android, iOS and ASP.net core w/ Razor page) with a view model and controller that handle all of the TCP/IP communication and updates the view model. The view model has an event that is fired when I get build output text over the TCP/IP connection. On the Windows, Android and iOS apps, I append a textbox with the incoming data.

How can I do the same thing for my ASP.net Razor page? There is a lot of text coming over the wire and I want it to update the textarea in real time as the evet fires with new text.

.Net Core 2.1 - T4 Template

$
0
0

Hi,

This is what exactly I want to achieve https://lennilobel.wordpress.com/category/c/ 

But in .Net Core 2.1; Database created using 


PM> Scaffold-DbContext "Server=xxxxx;Database=StarWars;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context "SWContext" -DataAnnotations

SWContext.cs

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace CoreProject.Models
{
public partial class SWContext : DbContext
{
public SWContext()
{
}

public SWContext(DbContextOptions<SWContext> options)
: base(options)
{
}

public virtual DbSet<Character> Character { get; set; }
public virtual DbSet<Climate> Climate { get; set; }
public virtual DbSet<EyeColor> EyeColor { get; set; }
public virtual DbSet<Gender> Gender { get; set; }
public virtual DbSet<HairColor> HairColor { get; set; }
public virtual DbSet<Planet> Planet { get; set; }
public virtual DbSet<SkinColor> SkinColor { get; set; }
public virtual DbSet<Terrain> Terrain { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=xxxx;Database=StarWars;Trusted_Connection=True;");
}
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Character>(entity =>
{
entity.HasIndex(e => new { e.Id, e.ClimateId })
.HasName("idx_Climate");

entity.HasIndex(e => new { e.Id, e.EyeColorId })
.HasName("idx_EyeColor");

entity.HasIndex(e => new { e.Id, e.GenderId })
.HasName("idx_Gender");

entity.HasIndex(e => new { e.Id, e.HairColorId })
.HasName("idx_HairColor");

entity.HasIndex(e => new { e.Id, e.SkinColorId })
.HasName("idx_SkinColor");

entity.HasIndex(e => new { e.Id, e.TerrainId })
.HasName("idx_Terrain");

entity.HasIndex(e => new { e.Id, e.GenderId, e.SkinColorId, e.HairColorId, e.EyeColorId, e.ClimateId, e.TerrainId })
.HasName("idx_Character");

entity.HasOne(d => d.Climate)
.WithMany(p => p.Character)
.HasForeignKey(d => d.ClimateId)
.HasConstraintName("FK_Character_Climate");

entity.HasOne(d => d.EyeColor)
.WithMany(p => p.Character)
.HasForeignKey(d => d.EyeColorId)
.HasConstraintName("FK_Character_EyeColor");

entity.HasOne(d => d.Gender)
.WithMany(p => p.Character)
.HasForeignKey(d => d.GenderId)
.HasConstraintName("FK_Character_Gender");

entity.HasOne(d => d.HairColor)
.WithMany(p => p.Character)
.HasForeignKey(d => d.HairColorId)
.HasConstraintName("FK_Character_HairColor");

entity.HasOne(d => d.SkinColor)
.WithMany(p => p.Character)
.HasForeignKey(d => d.SkinColorId)
.HasConstraintName("FK_Character_SkinColor");

entity.HasOne(d => d.Terrain)
.WithMany(p => p.Character)
.HasForeignKey(d => d.TerrainId)
.HasConstraintName("FK_Character_Terrain");
});

modelBuilder.Entity<Planet>(entity =>
{
entity.HasOne(d => d.HomeWorld)
.WithMany(p => p.Planet)
.HasForeignKey(d => d.HomeWorldId)
.HasConstraintName("FK_Planet_Character");
});
}
}
}

My ClassGender.tt

<#@include file="EnumsDb.ttinclude" #>
<#
  var configFilePath = "app.config";
 
  var enums = new []
  {
    new EnumEntry
      ("Genders", "DemoDatabase", "dbo", "Gender", "Id", "Name")
      { GenerateUndefinedMember = true },
 
    new EnumEntry
      ("System error types", "DemoDatabase", "dbo", "EyeColor", "Id", "Name")
      { GenerateUndefinedMember = true },
 
  };
 
  var code = this.GenerateEnums(configFilePath, enums);
 
  return code;
#>

app.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <connectionStrings>
    <add name="DemoDatabase" connectionString="Data Source=xxxx;Initial Catalog=StarWars;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

But, seem not working.

Then, I try to look into this but stuck:- 

https://stackoverflow.com/questions/37679367/entity-framework-core-customise-scaffolding

Please advise.

Thank you.

Regards,

Micheale


Visual studio 2015 on windows 10 keep getting error

$
0
0

I keep getting the below error in visual studio2015, I have tried one of the suggesstions below but it has not helped

http://www.talkingdotnet.com/how-to-fix-dnx-project-start-up-error-in-vs-2015/

---------------------------
Microsoft Visual Studio
---------------------------
The following error occurred attempting to run the DNX design time process (dnx-clr-win-x86.1.0.0-rc1-update1).



A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [::ffff:127.0.0.1]:49637



The DNX design time process provides intellisense, build, and reference information to Visual Studio and without it your experience will be very limited. Please try closing and reopening Visual Studio to see if that corrects the problem. Alternatively, check that the DNX version is properly installed or try changing to a different installed DNX version using the project property pages.
---------------------------
OK   
---------------------------

On dropdown change render a partial razor page view in CORE 2.1 RAZOR PAGE MVC

$
0
0

I want to be able to pass  a  string  id   to  a method on the partial  razor page. The partial page  will then call the Web API which
returns  a model object. In the behind code of the partial page I  am trying to render a  simple input based on the  model values I got  from the Web API f of the  partial page.  I want to then render  the partial page inside my main page  under a specific  div tag id.

Can anyone provide me with a code example?

Thanks,

Only one user get HttpContext Null error. Need Help!!

$
0
0

Hi experts,

I have an Asp.Net Core 2.1 web application running on Windows Server 2008 R2.
Everyone have access to this web app but only one person gets "System.NullReferenceException: Object reference not set to an instance of an object." forHttpContext
Weird this is, he can access the same application that running on test server which is same Windows Server 2008 R2 
I indicated the line where error out in yellow highlight in Session class code.

I spent many days to fix it, but no luck yet.

Please help, and thank you in advance.

Here is my Startup.cs:

public class Startup {
	static public IConfigurationRoot Global { get; set; }
        public IHostingEnvironment HostingEnvironment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IHostingEnvironment env, IConfiguration configuration) {
            try
            {
                HostingEnvironment = env;
                Configuration = configuration;
                this.SetGlobals(HostingEnvironment);
            }catch(Exception ex)
            {
                //If failed in here, it needs special error handler
                Helper.errorMsg msg = new Helper.errorMsg();
                Helper.CreateRfs_LostHosting(ex, -1, msg).Wait();
            }
	}

	public void ConfigureServices(IServiceCollection services) {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

	    services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromHours(12);
            });
	    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
	}


	public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
	    if (env.IsDevelopment()) {
		app.UseDeveloperExceptionPage();
		app.UseBrowserLink();
	    } else {
		app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();

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

            Session.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
	}
}

I have a Session Class:

public class Session
    {
		private static IHttpContextAccessor _httpContextAccessor;

		public static void Configure(IHttpContextAccessor httpContextAccessor) {
			_httpContextAccessor = httpContextAccessor;
		}

		public static void Initialize() {
			var sessionUser = Session.GetSessionObj<SessionUser>("SessionUser");
			if (sessionUser == null) {
				sessionUser = new SessionUser();sessionUser.Initialize(HttpContext);
				Session.SetSessionObj("SessionUser", sessionUser);
			}
		}

		public static HttpContext HttpContext { get { return _httpContextAccessor.HttpContext; } }
		public static SessionUser SessionUser { get { return Session.GetSessionObj<SessionUser>("SessionUser"); } }
		public static bool UserValidated { get {
                if (SessionUser == null)
                {
                    Initialize();
                }
                return SessionUser.Validated;
            } }

		public static void SetSessionVar(string key, string value) {
			_httpContextAccessor.HttpContext.Session.SetString(key, value);
		}

		public static void SetSessionObj(string key, object value) {
			_httpContextAccessor.HttpContext.Session.SetObject(key, value);
		}

		public static T GetSessionObj<T>(string key) {
			var sessionObj = _httpContextAccessor.HttpContext.Session.GetObject<T>(key);
			return sessionObj;
		}
    }

here is SessionUser class:

public class SessionUser
    {
	public void Initialize(HttpContext httpContext) {
		string userName = null;
		var identity = httpContext.User.Identity;

		if (identity.IsAuthenticated) {
			userName = identity.Name;
		} else {
			var basicCredentials = new BasicAuthenticationHeader(httpContext);
			userName = basicCredentials.UserName;
		}
        }
    }

Only one person gets HttpContext Null error. [Sorry it is duplicated upload]

$
0
0

Sorry it is duplicated upload original thread: original thread
Hi experts,

I have an Asp.Net Core 2.1 web application running on Windows Server 2008 R2.
Everyone have access to this web app but only one person gets "System.NullReferenceException: Object reference not set to an instance of an object." forHttpContext
Weird this is, he can access the same application that running on test server which is same Windows Server 2008 R2 
I indicated the line where error out in yellow highlight in Session class code.

I spent many days to fix it, but no luck yet.

Please help, and thank you in advance.

Here is my Startup.cs:

public class Startup {
	static public IConfigurationRoot Global { get; set; }
        public IHostingEnvironment HostingEnvironment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IHostingEnvironment env, IConfiguration configuration) {
            try
            {
                HostingEnvironment = env;
                Configuration = configuration;
                this.SetGlobals(HostingEnvironment);
            }catch(Exception ex)
            {
                //If failed in here, it needs special error handler
                Helper.errorMsg msg = new Helper.errorMsg();
                Helper.CreateRfs_LostHosting(ex, -1, msg).Wait();
            }
	}

	public void ConfigureServices(IServiceCollection services) {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

	    services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromHours(12);
            });
	    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
	}


	public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
	    if (env.IsDevelopment()) {
		app.UseDeveloperExceptionPage();
		app.UseBrowserLink();
	    } else {
		app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();

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

            Session.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
	}
}

I have a Session Class:

public class Session
    {
		private static IHttpContextAccessor _httpContextAccessor;

		public static void Configure(IHttpContextAccessor httpContextAccessor) {
			_httpContextAccessor = httpContextAccessor;
		}

		public static void Initialize() {
			var sessionUser = Session.GetSessionObj<SessionUser>("SessionUser");
			if (sessionUser == null) {
				sessionUser = new SessionUser();sessionUser.Initialize(HttpContext);
				Session.SetSessionObj("SessionUser", sessionUser);
			}
		}

		public static HttpContext HttpContext { get { return _httpContextAccessor.HttpContext; } }
		public static SessionUser SessionUser { get { return Session.GetSessionObj<SessionUser>("SessionUser"); } }
		public static bool UserValidated { get {
                if (SessionUser == null)
                {
                    Initialize();
                }
                return SessionUser.Validated;
            } }

		public static void SetSessionVar(string key, string value) {
			_httpContextAccessor.HttpContext.Session.SetString(key, value);
		}

		public static void SetSessionObj(string key, object value) {
			_httpContextAccessor.HttpContext.Session.SetObject(key, value);
		}

		public static T GetSessionObj<T>(string key) {
			var sessionObj = _httpContextAccessor.HttpContext.Session.GetObject<T>(key);
			return sessionObj;
		}
    }

here is SessionUser class:

public class SessionUser
    {
	public void Initialize(HttpContext httpContext) {
		string userName = null;
		var identity = httpContext.User.Identity;

		if (identity.IsAuthenticated) {
			userName = identity.Name;
		} else {
			var basicCredentials = new BasicAuthenticationHeader(httpContext);
			userName = basicCredentials.UserName;
		}
        }
    }

Calling RabbitMQ from .NET CORE Web API

$
0
0

Dear Friends,

I hope, this not wrong forum for my question. I am calling RabbitMQ from .ASP.NET core web API but it is giving me following error:

RabbitMQ.Client.Exceptions.BrokerUnreachableException: 'None of the specified endpoints were reachable'

ExtendedSocketException: No connection could be made because the target machine actively refused it 127.0.0.1:5672

I have following code which works perfectly for .NET Core Console app:

ConnectionFactory connectionFactory = new ConnectionFactory();

connectionFactory.Port = 5672;
connectionFactory.HostName = "localhost";
connectionFactory.UserName = ""; // User name
connectionFactory.Password = ""; //password
connectionFactory.VirtualHost = "/";

IConnection connection = connectionFactory.CreateConnection();
IModel channel = connection.CreateModel();
//Console.WriteLine(string.Concat("Connection open: ", connection.IsOpen));

channel.ExchangeDeclare("my.first.exchange", ExchangeType.Direct, true, false, null);
channel.QueueDeclare("my.first.queue", true, false, false, null);
channel.QueueBind("my.first.queue", "my.first.exchange", "");

channel.Close();
connection.Close();

Any suggestion please?

Thanks,

Pervaiz Khan.

Trying to use IIS 8.5 to host ASP.NET Core 2.1 Web application

$
0
0

When I try to run an ASP.Core Web application on IIS 8.5  I get an HTTP Error 500.19

None of the answers in the Microsoft docs or forums solves the problem.

I made a Web app with custom Identity authentication and got nowhere when I tried to deploy it. Then I simply made an app from the Visual Studio 2017 Web Application template with https enabled. Same result—500.19.

It seems that IIS cannot find the app files. The error details point to the web.config file but the file is exactly what I’ve seen in numerous samples and forums.

In IIS I created an AppPool with .NET CLR verson set to No Managed Code. Identity set to NetworkService.

I installed the .NET Core Server Hosting bundle and Microsoft.Net Core SDK 2.1.301 (x64) [I know, I only need the runtime)

IIS_IUSRS has read/execute permissions.

Starting Kestrel on the server and then trying to access the web site from a browser on another computer does not work.

I tried setting the processPath in web.configto dotnet.exe: C:\Program Files\dotnet\dotnet.exe

I tried publishing Web app both as Self-contained and then as Framework-Dependent

I used Visual Studio 2017 15.7.5 Publish command in the Build menu.

I put the published files in a folder with the application’s name in c:\inetpub\wwwroot

Here’s one version of Startup I tried:

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.AddTransient<IUserStore<ApplicationUser>, UserStore>();
            services.AddTransient<IRoleStore<ApplicationRole>, RoleStore>();

            services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
            {
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase = false;
                options.Password.RequiredLength = 8;
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
            })
                .AddDefaultTokenProviders();

            // Add application services.
            services.AddSingleton<IConfiguration>(Configuration);
            services.AddTransient<IEmailSender, EmailSender>();
            services.AddTransient<ISelectListRepository, CarrierRepository>();
            services.AddMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(10);
                options.Cookie.HttpOnly = false;
            });
            services.Configure<IISOptions>(options =>
            {
                options.AutomaticAuthentication = false;
                options.ForwardClientCertificate = false;
            });
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddHsts(options =>
            {
                options.Preload = true;
                options.IncludeSubDomains = true;
                options.MaxAge = TimeSpan.FromDays(60);
            });
            services.AddHttpsRedirection(options =>
            {
                //options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                options.HttpsPort = 443;
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

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

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

Is it permissions? Is it the path to dotnet? Is it the config?

I would appreciate your help.  Thanks.

Razor Pages Multiple Ajax (Virtual Forms)

$
0
0

I have developed a kind of server side programming for myself In Asp.Net MVC Core with using "Unobtrusive Ajax" (that is available as a separate download in Core). and here is how:

For the View Model I divide it in to multiple "Sub Models" with each sub model is responsible to render a separate Ajax Form (or Ajax Link) on the View. Each Ajax form then Posts or Gets an action method and Replaces a "Partial View" inside any <Div id="###"></Div> that is mentioned in the form, for example:

<form asp-controller="Admin" asp-action="ListArticleTypes" id="refreshTable"
          data-ajax="true" data-ajax-method="GET"
          data-ajax-mode="replace" data-ajax-update="#TableDiv"

The Div (that replaces with a partial view) can be in any place on the View, Even a div enclosing the form itself.

With this technique and a few other ones, I can do everything that could be done with Html Controls in MVC Core (in a Server Side manner that I think many Like). Is this possible in Razor Pages?


Access HttpContext in HostedService

$
0
0

I need to have access to the HttpContext in the background service to scan the composition. But when I register "IHttpContextAccessor", in the service IHttpContextAccessor->HttpContext is null


simple start project


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

services.AddSession();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();


services.AddMvc();
services.AddHostedService<TestDI>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor httpContextAccessor)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseMvc();
}

make project work in two diffrent browser should affect in each other ???????

$
0
0

as I write in the title I made a full user log in system put when I want to try to use two different account in different browser one of them change to other account so what is the problem or that just because I work with visual studio and in upload the website to server every thing will work will 

hosting on linux questions

$
0
0

hi,

i am a little confused on how .net core work on linux system .

i want to setup a vps linux machine to host my .net core application that interact with existing firebird databases .

1 - do i need apache on the server ? or my web application is a self contained app containing an integrated web server .?

2 - i want to host several customers in this vps, each customer  have it's own firebird database 

the number of customers is about 20, and each one can have 20-30 users per day mainly for readonly operations.

is it better to make ONE web application to handle all differents customers and their respective databases ,

or to make a web application per customer .

thanks .

Saving Http POST data to database - 500 error

$
0
0

I am a beginner at ASP.NET.  I am trying to POST JSON array to the controller and save the same to the database. I am getting a 500 error on POST. Help and direction appreciated- regards @itsmeabhilashgk. The build is successful but I am getting a 500 error saying failed to load resource. I have given the Model,Controller I am trying to POST data to and also the JSON being passed. I checked through debugger, the gitjson is null. I have also given the obj in ajax call as shown in debugger .

publicclassGitcontroller:Controller{private readonlyGithubContext _context;publicGitcontroller(GithubContext context)//the database context{
            _context = context;}[HttpPost]publicIActionResultUpdateto([FromBody]GitJSON gitjson){try{if(ModelState.IsValid){
                    _context.AddRange(gitjson);
                    _context.SaveChanges();//adding list to table.}returnView();}catch(Exception ex){returnRedirectToPage("Error", ex);}}

namespace Github.Models{publicclass gitd{publicint ID { get;set;}publicstringAvatarURL{ get;set;}publicstringName{ get;set;}publicdecimalScore{ get;set;}publicDateTimeUpdatedat{ get;set;}}publicclassGitJSON{publicList<gitd> gitdList {set; get;}}}
ajax call- obj as seen in Watch:
 Object {gitdList: "[{"AvatarURL":"avatars1.githubusercontent.…"}

ajax call to POST:
$.ajax({
                        type:'POST',
                        url:'http://localhost:60294/Git/Updateto',
                        contentType:'application/json; charset=utf-8',
                 datatype:'JSON',
                 data: obj,
                       success: function (data){
                            alert('Post Succesful');},
                        error: function (data){
                            alert('error');}});
 
>(1,2): error CS0246:The type or namespace name 'HttpPostAttribute'> could not be found (are you missing a using directive or an assembly> reference?)(1,2): error CS0246:The type or namespace name 'HttpPost'> could not be found (are you missing a using directive or an assembly> reference?)(2,17): error CS0246:The type or namespace name>'IActionResult' could not be found (are you missing a using directive> or an assembly reference?)(2,41): error CS0246:The type or namespace> name 'FromBodyAttribute' could not be found (are you missing a using> directive or an assembly reference?)(2,51): error CS0246:The type or> namespace name 'GitJSON' could not be found (are you missing a using> directive or an assembly reference?)>+ additional 6 errors
> using Microsoft.AspNetCore.Mvc; using Github.Models; using System;> using System.Collections.Generic; using System.Linq; using>System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering;> using Microsoft.EntityFrameworkCore;
gitdList:[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225? v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
 

Populating a Modal with a working form just using Razor Pages..possible?

$
0
0

Hi,

is it possible to populate a bootstrap modal with a working insert/edit form comprised of a partial page or view component instead of using Ajax?

I can do this with Ajax but would like to know if this can be achieved in razor pages, I am experimenting but think my unfamiliarity with Razor is letting me down.

Thanks for any input

Viewing all 9386 articles
Browse latest View live


Latest Images

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