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

Reset textbox on view and partial view.

$
0
0

 I'm trying to reset two textboxes in a partial when I click 'Add and Create Another' button and can't get them to reset.

View

<div class="row"><div class="col-md-7 order-md-8"><div class="row"><div class="col-md-12"><h2 class="text-info">@ViewData["Title"]</h2><hr /><div class="row"><div class="col-md-12"><form id="form-create-link"
                              method="post"
                              enctype="multipart/form-data"
                              asp-controller="Link"
                              asp-action="CreateLink"><partial name="_ClientStatusMessage" /><div id="add-link"><partial name="_AddLink" model="@Model" /></div></form></div></div></div></div></div>

Partial View (this is where textboxes are)

<div class="form-group col-md-8"><div asp-validation-summary="All" id="validation-error" class="text-danger custom-validation-summary"></div></div><input id="link-id" asp-for="@Model.LinkId" type="hidden" /><a name="link"></a><partial name="_StatusMessage" model="@statusMessage" />
@*<input type="hidden" asp-for="LinkId" />*@<div class="form-group col-md-12 col-lg-12"><div class="row"><div class="form-group col-md-3"><a class="btn btn-forum"
               asp-area="Admin"
               asp-controller="Link"
               asp-action="Index"><i class="fa fa-arrow-circle-left fa-lg fa-fw"></i>
                Back to Links</a></div></div></div><div class="form-group col-md-8 col-lg-4"><label class="control-label">Display Order</label><div><input id="displayOrder" asp-for="Order" name="displayorder" class="form-control" /></div></div><div class="verticalspace"></div><div class="verticalspace"></div><div class="form-group col-md-8 col-lg-4"><label class="control-label" asp-for="CategoryId"></label><div><select asp-for="CategoryId"
                asp-items="Model.AvailableCategories" class="form-control"></select></div></div><div class="verticalspace"></div><div class="verticalspace"></div><div class="form-group col-md-8 col-lg-4"><label class="control-label">Title</label><input id="link-title" asp-for="Title"  class="form-control" /></div><div class="verticalspace"></div><div class="verticalspace"></div><div class="form-group col-md-8 col-lg-4"><label class="control-label">URL</label><input id="link-url" asp-for="URL"  class="form-control" placeholder="https://example.com" /></div><div class="verticalspace"></div><div class="verticalspace"></div><div class="form-group col-md-8 col-lg-12"><label class="control-label">Description</label><textarea class="rtextLinkDescription" name="Description" id="Description" row="1" cols="60"
              data-val-maxlength-max="200" asp-for="Description"
              data-val-maxlength="Max length for Description is 200"></textarea></div><div class="form-group col-md-12"><a href="#link"
       id="link-save-and-add-another"
       type="button"
       class="btn btn-forum col-sm-12 col-md-4 col-lg-4">Add & Create Another</a><a id="link-submit"
       class="btn btn-forum col-sm-12 col-md-4 col-lg-4">Add & Return to Links</a><a id="link-cancel"
       class="cancel btn btn-forum col-sm-12 col-lg-3">Return to Links</a></div>

js file:

$(document).ready(function ($) {$('.rtextLinkDescription').richText();
});$(document).on("click",
    '#link-save-and-add-another',
    function (e) {
        blockUI();
        var post_url = $("#form-create-link").attr("action"); //get form action url
        var request_method = $("#form-create-link").attr("method"); //get form GET/POST method
        var form_data = new FormData($("#form-create-link")[0]);$("#link-is-create-only").val(false);$.ajax({
            url: post_url,
            type: request_method,
            data: form_data,
            processData: false,
            contentType: false,
            async: true
        }).done(function (objOperations) {$("#add-link").html(objOperations);
            if ($("#validation-error")[0].textContent.trim() === "") {$('#form-create-link').reset("reset");$('.rtextLinkDescription').richText();$('#link-is-create-only').click(function () {$(".rtextLinkDescription").val('').trigger("change");;
                });
            }$.unblockUI();
        });
    });

jQuery.fn.reset = function () {
    $("#CategoryId").prop('selectedIndex', 0);$("#link-title").val("");$("#link-url").val("");$(".rtextLinkDescription").val('');$("#displayOrder").val(0);
}


How can I access the ssl certificate of my asp.net core app

$
0
0

Dear All,

Please I built my web service with asp.net core 3.1. I am using a java application to connect to this web service. But I get this exception when I try to connect to the webservice application endpoint

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetsun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Please how do I get to access the ssl certificate. Also do I need to generate a public key when connect with the web service. I want all connection to be powered over https.

Need your advice. Thanks.

Thanks alot.

IOptionsMonitor doesn't work with custom ConfigurationProvider after upgrade from 2.2 to 3.1

$
0
0

I have a class CustomConfigurationProvider : ConfigurationProvider

with the method:

public override void Load()

{

    // Load values into this.Data

    ...

    //

    this.OnReload();

}

This loads options classes that are configured in startup:

services.Configure<MyOptions>(this.Configuration.GetSection("path:to:myOptions"));

Then I inject an IOptionsMonitor<MyOptions> into the class that needs these options.

This was all working fine in .NET core 2.2, with the IOptionsMonitor getting new values when they were updated.  After upgrading to 3.1, I see the CustomConfigurationProvider load new values into the dictionary and call OnReload, but the IOptionsMonitor never gets new values.

An IOptionsSnapshot will get new values, so it seems the provider is loading them correctly.  The IOptionsMonitors just never get notified, and I can't use snapshots everywhere because I have a singleton taking options.

Am I missing something?  Maybe related to ChangeTokens?

MQTT Authentification in Asp .Net Core 3.1

$
0
0

Hello can anyone advise how to implement Authentification(username and password FROM DB level) in MQTT platform, currently have few ideas in mind:

1. Authenticate on every message received from client, problem is database would get huge load just for checking if many users are provide valid login data.

2. Implement other authentication solution(JWT?), then how to implement in current solution(link to github)

There are two projects one Asp .Net core MQTT "server" and other .Net Core Console App "client"

Github link to plain MQTT implementation(Mosquitto config also included if anyone needs it)

Github

Thanks for help.

How to make global variables on asp.net core 2 on level of all project web API ?

$
0
0

problem

How to make global variables on asp.net core 2 on level of all project web API ?

I work on asp.net core 2.1 project web API 

i have more controller and i need to use global variables for all solution or project shared CompanyCode value

so that how to do that on asp.net core 

so that how to make company code as global variables or session or shared if i call it in any controller i can get values ?

issues faced while extend Role based authorization

$
0
0

Hello ,

i faced issues when i tried to extend role based authorization by using Microsoft identity.

when call login action method it will generate token if not added role into claim List.

   var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,user.UserName),
                new Claim(ClaimTypes.NameIdentifier,user.Id.ToString())
            };var roles = await _userManager.GetRolesAsync(user);  // If remove this await call then it work fine.

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

After add new role intoClaims while generate Token and i did get any response from server for few min after some time it will shown error like below. 

Error is :  Exception has been thrown by the target of an invocation.

In Startup.cs class under ConfigureServices Method.

 services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
            {
                opt.Password.RequireDigit = false;
                opt.Password.RequiredLength = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores<DataContext>();
            builder.AddRoleValidator<RoleValidator<Role>>();
            builder.AddRoleManager<RoleManager<Role>>();
            builder.AddSignInManager<SignInManager<User>>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(auth =>
            {
                auth.TokenValidationParameters = new TokenValidationParameters()
                {
                    // ValidateIssuer = true,
                    // ValidIssuer = Configuration["AuthSettings:Issuer"],
                    // ValidateAudience = true,
                    // ValidAudience = Configuration["AuthSettings:Audience"],
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["AuthSettings:Key"])),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });   services.AddControllers(opt =>            {                var policy = new AuthorizationPolicyBuilder()           .RequireAuthenticatedUser()           .Build();                opt.Filters.Add(new AuthorizeFilter(policy));            })             .AddNewtonsoftJson(options =>              options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

In AuthController 

        [HttpPost("login")]
        public async Task<IActionResult> Login(UserForLoginDto loginDto)
        {
            var user = await _userManager.FindByNameAsync(loginDto.Username);
            var result = await _signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false);
            if (result.Succeeded)
            {
                var appUsers = await _userManager.Users.Include(e => e.Photos)
                .FirstOrDefaultAsync(next => next.NormalizedUserName == loginDto.Username.ToUpper());

                var userToReturn = _mapper.Map<UserForListDto>(appUsers);
                return Ok(new
                {
                    token = GeneratejwtToken(appUsers),
                    user = userToReturn

                });
            }
            else
            {
                return Unauthorized();
            }



        }

        private async Task<string> GeneratejwtToken(User user)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,user.UserName),
                new Claim(ClaimTypes.NameIdentifier,user.Id.ToString())
            };

            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["AuthSettings:Key"]));
            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.Now.AddDays(1),
                SigningCredentials = signingCredentials

            };
            var TokenHandler = new JwtSecurityTokenHandler();
            var token = TokenHandler.CreateToken(tokenDescriptor);
            return TokenHandler.WriteToken(token);
        }




Can run API in Azure but not on local machine in IIS - 500.31 error

$
0
0

So I have been running my new API in Azure successfully (Xamarin and WPF clients using it).  My employer wants me to run the API on a local server which means I have to first get it to run in IIS on my local machine (which I haven't done since early stages of writing the API).  But now I am getting the error:  HTTP Error 500.31 - ANCM Failed to Find Native Dependencies.  The error gives a lot of ideas to fix, none of which make any sense at all to me. I have installed the Net Core 3.1 web hosting bundle (several times just in case) and that doesn't help.   I have tried researching the recommendations to try to understand them, but have not found any answers.  My over two-year project for my employer is dead in the water at this point and I really need help.    

Fetching form data and obtaining response

$
0
0

I am writing an app that allows one to upload several files and that has a table in the view dinamically updated according to the uploading.

Thus, I have a view with a form like this:

<form id="AddAttachmentFrm" enctype="multipart/form-data" onsubmit="afFileSubmitAjax(this); return false;" >
...<input type="submit" id="AddAttachment" name="AddAttachment" class="btn btn-primary" value="Upload" />
...</form>

The form submission triggers the following JavaScript method:

        async function afFileSubmitAjax(oFormElem) {
            const formData = new FormData(oFormElem);

            var response = await fetch("@Url.Action("PostFile","Home")", {
                method: 'POST',
                body: formData
            });

My controller contains the following function which deals with /Home/PostFile:

        [HttpPost]
        public JsonResult PostFile(IFormCollection form)
        {
            string id = "Error";

            try
            {
                IFormFile file = form.Files[0];
                string filename = Path.GetFileName(file.FileName);

                if (file.Length > 1048576)
                    return Json(String.Empty);
                FileCacheModel fcitem = AddTempFile(filename, file, comment);

                id = fcitem.id; // an unique id

                AddFileToDatabase(fcitem);
            }
            catch
            {
                return Json(String.Empty);
            }

            return Json(id);
        }

Now I would like to obtain the information that comes in the end of the function (return Json(id)). How can I accomplished that? 

I tried to see the variable response of the JavaScript snippet, and I can't find the information the method returns.

Could you help me?


how do i get the generic type?

$
0
0

hi

lets say i have

var someValue = List<SomeClass>(); //SomeClass inherits from BaseClass

i want to get what type is in the list (eg SomeClass) and then find if it inherits from baseclass

this is what i have but its not working

PropertyInfo prop;

if(prop.PropertyType.GetGenericTypeDefinition().IsSubclassOf(typeof(BaseClass))

but GetGenericTypeDefinition doesn't do what i thought, and googling is getting me no where fast.

Any thoughts would e appriciated.

Host blazor in winforms or other application types

$
0
0

Hello,

I have a project where i want to host a server-side blazor in a winforms application (or any other).

I successfully did it, it works.

I created a blazor project, then changed it to class library, and called what is in the program.cs from an other class.

Everything is fine, it works, BUT :

Static assets (from project and third-party nugets) are not dumped when i build or publish the winforms app.

Is it possible to make it work ?

Thanks in advance.

can i cast to a generic type with base Classes?

$
0
0

Hi i have this

pulic class BackGroundClass<T,X> : BaseClass where T : AnotherBaseClass
                                             where X : AnotherBaseClass
{
}

public class MyClassA : BackGroundClass<FooA, BarA>// FooA and BarA both inherit from AnotherBaseClass<T,X>
{
}

public class MyClassB : BackGroundClass<FooB, BarB>// FooB and BarB both inherit from AnotherBaseClass<T,X>
{
}

public class MyClassC : BackGroundClass<FooC, BarC>// FooC and BarC both inherit from AnotherBaseClass<T,X>
{
}

now what i want to is is have one list which contains multiple instances of MyClassA, MyClassB and MyClassC

i would be happy with

var myList = new List<BackGroundClass<AnotherBaseClass, AnotherBaseClass>>()

but if I do

var myClassC = new MyClassC ();

myList.Add(myClassC);

it doesn't work and myList is null

doing

someMethod( myClassC as BackGroundClass<AnotherBaseClass, AnotherBaseClass>)

also doesn't work

any suggestions would be appriciated.

New column added for table when inhereting IdentityUserClaim

$
0
0

I have a basic class that inherits IdentityUserClaim<int>. When I do a migration it adds a column named UserId1, but this column isn't visible any other place. The bad thing is that when calling RoleManager.GetClaimsAsync(User) it references this column when the rest of the system uses the standard UserId column.

Class:

public class UserClaim : IdentityUserClaim<int>
{
	public UserClaim() { }

	public UserClaim(int userId, string type, string value, int? siteId) : this(userId, new Claim(type, value), siteId) 
	{
		this.SiteId = siteId;
	}

	public UserClaim(int userId, Claim claim, int? siteId) {
		this.UserId = userId;
		this.SiteId = siteId;
		this.ClaimType = claim.Type;
		this.ClaimValue = claim.Value;
	}

	[PersonalData]
	public bool Active { get; set; } = true;
	[PersonalData]
	public Guid UId { get; set; } = Guid.NewGuid();
	public int? SiteId { get; set; }
	[PersonalData]
	public DateTime DateCreated { get; set; } = DateTime.Now;
	[PersonalData]
	public DateTime? DateDeleted { get; set; }

	[NotMapped]
	public Claim Claim => new Claim(this.ClaimType, this.ClaimValue);
}

Table:

CREATE TABLE [dbo].[IdentityUserClaim](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NOT NULL,
	[ClaimType] [nvarchar](max) NULL,
	[ClaimValue] [nvarchar](max) NULL,
	[Active] [bit] NOT NULL,
	[UId] [uniqueidentifier] NOT NULL,
	[SiteId] [int] NULL,
	[DateCreated] [datetime2](7) NOT NULL,
	[DateDeleted] [datetime2](7) NULL,
	[UserId1] [int] NULL,

localization In .Net Core

$
0
0

Hi, 
i use IViewLocalizer 
and i have duplicate text in most views that i duplicate it in any resources file

how can i set a common resources file for all view ?  

Instrumentation Profiler in CoreCLR(.Net Core) - Ways to get HttpContext in .NetStandard assembly

$
0
0

I am trying to Instrument .NET Core web applications that runs on .NET Core 3.1 using CoreCLR Profiler.
When I allow injecting the code into the Web application's method the helper assembly(.NET standard 2.0) is got attached to dotnet.exe process and it is getting callbacks to the helper assembly.
I have created helper assembly(.NET standard 2.0) with the injected functions body.

Now I need to get the HttpContext.Current of the each HTTP request of .NET core web application in helper assembly(.NET standard 2.0). In .Net framework we have System.Web.HttpContext.Current and System.Web.HttpRequest to get the Header,cookie,session id and site name of each request. How can I achieve same in .Net standard? 

1. Can I use Microsoft.AspNetCore.Http.HttpRequest in .NET standard 2.0 assembly? If so how can I add reference to .Net standard assembly?
2. How can I get Header,cookie,session id and site name of .net core web application in .NET standard 2.0 assembly?
3. What is the alternative/equivalent of following .Net Framework namespaces in .Net Core/.Net 
     A. System.Web.HttpContext.Current
     B. System.Web.HttpRequest
     C. System.Web.HttpCookie
     D. System.Web.Hosting.HostingEnvironment.SiteName

It would be much helpful if i get some correct direction to get or use HttpContext.Current in .NetStandard assembly.

Thanks in advance. 

Can one serve "static" but external content underneath an asp.net.core application

$
0
0

We've got an application that we deploy on Linux.  It's a self contained application that is started up from systemctl and uses Kestrel.  This is the "server side" code, but in this picture there is a client side application that needs to be hosted.  My hope was to serve that client side code from the same Kestrel process by being able to reference a directory on the filesystem.  But, that content isn't resident at compile time and would be placed there for serving after the server piece was in place (and may be updated as development occurs.)

So after some unsuccessful experimentation based on forays into the documentation I landed here wondering if A) is this even possible and B) what should I look at to go about doing such.

I have my fall-back of using nginx, but if I could not have to install that on machines that would be great.

In the app, here is the context of how we define our Kestrel (with much stuff related to certs, ports, etc. omitted) with one of my failed attempt at referencing an external location.  Note:  There is no wwwroot or content used by the server app, everything is all API calls via controllers.

WebHost.CreateDefaultBuilder(args) 
    .UseStartup<Startup>()
    .UseKestrel()
    .ConfigureKestrel((context, options) =>
    { //omitted lots of stuff for brevity
    })
    .UseContentRoot("/var/foo/webapi/client") //A sample attempt at adding a location where client code lives.
    .UseNLog()
    .Build();


blazor application architecture

$
0
0

Still a total noob to Blazor.  Trying to figure out if the following is possible. Or maybe am I crazy for trying to mash this altogether with blazor?

Customer:

  • a Progressive Web App for mobile
  • using most (or all?) of the same code for a server based web app for the customer who doesn't want to install a PWA 

Backend/Business:

  • back end server part of the application to handle business and admin functions
  • A PWA for backend users for certain functions

There PWA functions would do API calls, while the server parts could call the business layer directly.

Would authenticate the whole works with a mix of Identity (customer, external business users), OAuth (customer) and ADFS (business users only).

Was originally doing to native iOS/Android apps but building and deploying to the app stores is a pain in the ass.   The only thing the PWA's need from the mobile hardware is location, which I believe is possible.  No local database or anything needed. 

Value cannot be null. (Parameter 'connectionString')

$
0
0

Hi,

I am trying to link to my database. I am using aspnet.core 3.0 mvc.  I am using nu-get console and getting the above error.

Below is the appsettings.json:

"ConnectionStrings": {
"BumplesDBConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Bumples;Trusted_Connection=True;MultipleActiveResultSets=true"
},

Below is the startup:

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IMembersRepository, SQLMembersRepository>();

}

Below is the start of the error that I got in the console.

Build started...
Build succeeded.
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
at Bumples.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in C:\Users\Jennifer E Sheehan\source\repos\Bumples\Startup.cs:line 33
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_0`2.<AddDbContext>b__0(IServiceProvider p, DbContextOptionsBuilder b)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass10_0`1.<AddCoreServices>b__0(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)

Hope someone can help me, Thanks,

Jen

asp-page-handler is not able to call the post method in pagemodel

$
0
0

am trying to call a post method in my page model using asp-page-handler(binded into button). When i click on the button am getting 500 internal server error.Below is the code I tried.

Cshtml:

<form method="post" id="EditForm" class="form-horizontal">    <div class="col-xs-2 lead pull-right"><input type="submit" formmethod="post" value="Edit Employee" asp-page-handler="EditEmployee" asp-route-type="level1" class="btn btn-primary" /></div></form>

Cshml.cs (Page Model)

public IActionResult OnPostEditEmployee(string type)
{
	//Edit operation
}

After running the application the button is rendered as below

<input type="submit" formmethod="post" value="Edit Employee" class="btn btn-primary" formaction="Employee?type=level1&handler=DeleteCategory">

formaction for the button is wrong, Page handler should append to url first and it should be like formaction="Employee?handler=DeleteCategory&type=level1".

I tried calling the pagemodel method by removing the parameter type and for that also  am getting 500 internal server error.

 Note:  am using .net core 2.2 framework

Please help me to come out of this issue.

Thanks

How can I add blazor server-sdie into an exists asp.net core project?

$
0
0

I have made a website by asp.net core 3.1 before.

Now I wanna add a feature of 'contact us'.

After the users input their name/phone and click the submit button, the blazor server-side will send an e-mail of the user information above to my mailbox.

In spite, I can achieve this by Ajax, but now I want to do this by Blazor server-side.

I don't want to migrate the whole project to Blazor server-side for this feature only available on some page but not all the pages.

In my opinion, I will add blazor server-side into the asp.net core project which is existed.

I tried this by myself by adding the services.AddServerSideBlazor(); in ConfigureServices and adding the MapBlazorHub to UseEndpoints in Configure.

I only add a h3 element to the component of Blazor server-side and add the it to an existing page like this:

<component type="typeof(Project.Pages.Contact)" render-mode="ServerPrerendered" />

After I ran the project, it reports these errors in Chrome DevTools:

[2020-03-26T09:01:16.249Z] Error: Failed to complete negotiation with the server: Error
[2020-03-26T09:01:16.249Z] Error: Failed to start the connection: Error
[2020-03-26T09:01:16.250Z] Error: Error
Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State.
at e.send (blazor.server.js:1)
at e.sendMessage (blazor.server.js:1)
at e.sendWithProtocol (blazor.server.js:1)
at blazor.server.js:1
at new Promise (<anonymous>)
at e.invoke (blazor.server.js:1)
at e.<anonymous> (blazor.server.js:15)
at blazor.server.js:15
at Object.next (blazor.server.js:15)
at blazor.server.js:15

I googled and found it seems the SignalR of the project did not start correctly.

How can I solve this? Is there any tutorial about this? Thank you.

How Do I Block Data from Rendering in an API Controller?

$
0
0

I have an api controller that gets data from a service that returns more data than I want rendered in the json output, but I also need to access the same data from Razor Pages. How do I block that output at the controller level?

Normally I would just omit the data from the get task that the service performs, so that it would render as null in json output, but if I do that I can't access it from server side code in a Razor Page. The api controller is used because json is needed for an infinite scroll plugin. Otherwise I would not even need a controller.

Is there perhaps a quick line of code that can be added to a Controller that tells it to omit a specific field from the json output?

Here is the task redacted for efficiency from the Service file:

public async Task<Posts[]> GetPosts()
        { 
            var posts = await _context.Posts.Where(post => post.Active == true)
                            .Select(p => new Posts { 
                            Postid = p.Postid,
                            Title = p.Title,
                            Description = p.Description,
                            Userid = p.Userid 
                            })
                        .ToArrayAsync();
            return posts;
        }

A second task then paginates the results of the first one

public async Task<List<Posts>> GetPaginatedResult(int currentPage, int pageSize)
        {
            var data = await GetPosts();
            return data.OrderByDescending(d => d.Postid).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
        }

The controller is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PostAlmostAnything.Data;
using PostAlmostAnything.Models;
using PostAlmostAnything.SiteServices;
using PostAlmostAnything.AppCode;

namespace PostAlmostAnything.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PaginatedPostsController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public PaginatedPostsController(PostsService postService)
        {
            PostService = postService;
        }
        public PostsService PostService { get; }
 [HttpGet("{id:int}/{sid:int}")]
        public async Task<List<Posts>> GetPaginatedPostsAsync(int id, int sid)
        {
            int CurrentPage = id;
            int PageSize = sid;
            return await PostService.GetPaginatedResult(CurrentPage, PageSize);
        }

        
    }
}

Obviously there are reasons not to render the Userid field in the json output, but I also need to access the Userid in razor pages that need to get the UserName based on that id. I am using the default Identity tables in my database and those tables by default have no foreign key relationships with one another, so when they are scaffolded automatically they do not create navigation classes. Identity also stores the UserId as a string instead of a unique identifier like the old AspnetMembership provider did, so I'm not really sure how to go about creating a foreign key relationship between string values. I seem to recall trying to do that once and running into some kind of error message about SQL Server not supporting such relationships with strings. As a result I have another task called GetUserNambeById that I call from razor pages to populate UserName fields. This requires GetPosts to return the UserId so that it can be passed to GetUserNameById.

Viewing all 9386 articles
Browse latest View live


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