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

Two Factor Authentication, VerifyTwoFactorTokenAsync always return false

$
0
0

I tried creating a new project from VS 2017 (.Net Core v2.0) and for authentication, I chose 'Individual User Accounts'. I put QRCode from (https://davidshimjs.github.io/qrcodejs/). I put javascript code in EnableAuthenticator.cshtml

<script src="~/lib/qcrcode.js/qrcode.js"></script><script>
        new QRCode(document.getElementById("qrCode"),
            {
                text: "@Html.Raw(Model.AuthenticatorUri)",
                width: 200,
                height: 200
            }
        );</script>


In ManageController.cs, action method EnableAuthenticator doesn't change at all.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> EnableAuthenticator (EnableAuthenticatorViewModel model) {
            var user = await _userManager.GetUserAsync(User);
            if ( user == null ) {
                throw new ApplicationException ($"Unable to load user with ID '{_userManager.GetUserId (User)}'.");
            }

            if ( !ModelState.IsValid ) {
                await LoadSharedKeyAndQrCodeUriAsync (user, model);
                return View (model);
            }

            // Strip spaces and hypens
            var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

            //AuthenticatorTokenProvider
            var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                user, _userManager.Options.Tokens.EmailConfirmationTokenProvider, verificationCode);

            if ( !is2faTokenValid ) {
                ModelState.AddModelError ("Code", "Verification code is invalid.");
                await LoadSharedKeyAndQrCodeUriAsync (user, model);
                return View (model);
            }

            await _userManager.SetTwoFactorEnabledAsync (user, true);
            _logger.LogInformation ("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);
            var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
            TempData[RecoveryCodesKey] = recoveryCodes.ToArray ();

            return RedirectToAction (nameof (ShowRecoveryCodes));
        }

and this is QRCode generator

        private async Task LoadSharedKeyAndQrCodeUriAsync (ApplicationUser user, EnableAuthenticatorViewModel model) {
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            if ( string.IsNullOrEmpty (unformattedKey) ) {
                await _userManager.ResetAuthenticatorKeyAsync (user);
                unformattedKey = await _userManager.GetAuthenticatorKeyAsync (user);
            }

            model.SharedKey = FormatKey (unformattedKey);
            model.AuthenticatorUri = GenerateQrCodeUri (user.Email, unformattedKey);
        }

I run and register user, I get notification to 'update-database' to be executed in Package manager console, done. I register again and login successfully. In the 'Two-factors Authentication' menu, I clicked 'configure authentication app', go to 'enable authenticator' page scan QRCode through google/microsoft authenticator and always get fail with this error message:Verification code is valid

I tried to debug, I found VerifyTwoFactorTokenAsync() always return false. I don't know why this happen ? I tried to changed AuthenticatorTokenProvider became EmailConfirmationTokenProvider and still return false.

but I found something interesting that [TwoFactorEnabled] and [EmailConfirmed] columns in the dbo.AspNetUsers is false. 

are there any relation between value in the [TwoFactorEnabled] and [EmailConfirmed] columns and VerifyTwoFactorTokenAsync(), because one of the parameter is ApplicationUser ?

how to solve this problem ?


Error in Asp.Net Core 2.2 Web Application on Production Environment

$
0
0

Hello Everyone,

My Asp.Net Core 2.2 Web Site runs well locally and used to work on the production as well prior to upgrading to .net core 2.2 from core 1.1.

I get now an error while loading the Website in _ViewImports.cshtml that AccountViewModels and ManageViewModels could not be loaded.

I used the default stuff and have no custom code in the user Identity Model.

Here is the error, I would appreciate any help greatly! Thanks, kind blessings, Andreas 

Error

ASP.NET Core 2.x Identity - Multiple "Zones"

$
0
0

We've got an old webforms app that runs most of our business and we're in the process of re-writing this in ASP.NET Core for a number of reasons.  One of the things we'd like to do is migrate away from our homegrown security implementation and instead rely on ASP.NET Identity.  Our primary issue is that we have tens of thousands of accounts, each with 1 or more users assigned.  Each account has the same roles available to it (AccountOwner, SupportAdmin, BillingAdmin, etc).  This is defined in our Roles table as follows:

RoleID (AutoInc), AccountID, RoleName, RoleDescription

If a role is available to ALL accounts, we enter it is as follows:

0, AccountAdmin, Account Administrator

0, SupportAdmin, Support Administrator

0, BillingAdmin, Billing Administrator

... And so on, we have about 10 roles that we assign this way and are available to every single account we have.  We've got a couple of other accounts (primarily for our employees) that have more specific roles, for example:

1500, Employee, CompanyEmployee

Currently, we call a routine similar to this:

If(user.isinrole(UserID, AccountID, "AccountOwner")) {}...

From what I can tell, something like this is not available in ASP.NET Identity, making managing multiple accounts difficult.

This seems like it would be somewhat common, has anyone done this successfully (and securely) and if so, how?  Are we better off using ASP.Net Identity for authentication and our own routines for authorization?  What we've come up with is either:

1) Extending the Identity classes to include what we want, which doesn't appeal to us much as now we're relying on our custom code again vs a hardened authentication system

or 

2) Every time an account is created, create 10-15 new roles, for example: 1242_AccountOwner, etc (AccountOwner Role for accountID 1242).

Any input would be greatly appreciated.

Why I can't get the string in the webapi?

$
0
0

I created this webapi as below:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApplication1.Controller
{
    [Route("api/[controller]")]
    public class ValuesController : Microsoft.AspNetCore.Mvc.Controller
    {
        // GET: api/<controller>
        //[HttpGet]
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}

        // GET api/<controller>/5
        [HttpGet()]
        public IActionResult Get(string inputvalue)
        {
            return Ok("what you said is:"+inputvalue);
        }       
        // POST api/<controller>
        [HttpPost]
        public IActionResult Post([FromBody]string inputvalue)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }            
            return CreatedAtAction("Get", inputvalue);
        }

        // PUT api/<controller>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

I wanna whenever I post "How do you do", then the browser returns "what you said is: How do you do".

I followed the tutorial. But after I added a breakpoint I found that the IActionResult Get never works.

I want to upload the screenshot of Postman which using to test the webapi. However, It seems the forums cannot upload any image. In addition, the Postman only returns the string "how do you do?"

What's wrong with the code and how can I achieve it? Thank you.

How can I connect the Mysql database by EntityFrameworkCore?

$
0
0

I am a beginner of asp.net core. And now I created a database by MySQL.

Here are the columns:

int idUsers

string UserName

string Password

I found some incomplete tutorial said that I should install Microsoft.EntityFrameworkCore&Pomelo.EntityFrameworkCore.MySql in nuget first.

Secondary, add these string in appsetting.json:

{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
    }
  },"AllowedHosts": "*","ConnectionStrings": {"DefaultConnection": "server=localhost;port=3306;database=users;uid=Normal;password=Normal123!"
  }

}

And then I can hardly found any about more.

Most of the tutorial is about Microsoft SQLSERVER&SQLite. I know these more about than MySQL. Meanwhile, SQLSERVER needs money to buy it, and SQLite seems popular in off-line application but not online application.

Would you please tell me more about how to connect the Mysql database by EntityFrameworkCore? Thank you.

Cant seem to get started with 3.0 core ??? IN VS 2019

$
0
0

hi guys#

I wanted to try out the new 3.0 release and upgrade VS 2019. As I dont see it in the dropdown options when cxreating a new project.

I downloaded it here

https://dotnet.microsoft.com/download/dotnet-core/3.0 

using the x6x installer

And when installation is done, I run dotnet --version in command prompt and it tells me I still have version 2.2

This article and others say I should go to VS and enable it, but that option (with the checkbox) is not available on my version of VS2019 16.1.2)

The version on here is 2.2

https://dotnet.microsoft.com/download

Has anyone any solution around this or used 3.0 

many thanks

Ehi

Best Practice for Determining which Environment is Running at Runtime

$
0
0

Hi,

Still learning ASP.NET Core...

I am wondering what is the best practice for determining which environment is running at runtime for a specific scenario? 

My application writes a file to disk.  What I would like to happen is if I am running in dev locally on my machine then the file is written to a specific folder.  If running on production, I would like the file to be written to a different path/folder.  I haven't been able to figure out how I can test and then based on what environment I am in write to the correct path.

Any help would be appreciated.

Thanks,

Tim

Getting 'Can't find view' when invoking CreateAsync on UserManager (Identity)


.NET Core Database Operation Failed when logging in

$
0
0

I have 2 applications:

  1. ManagementStudio
  2. DocumentStudio

DocumentStudio references ManagementStudio dlls. The account management function is located in ManagementStudio so if I want to login from DocumentStudio, its tied to one of the dlls within ManagementStudio.

Right now, this is the error I get when I try to login from DocumentStudio:

enter image description here

Previously I have already run all migrations for ManagementStudio. However, I discovered that if I go back and add another migration, I'll suddenly have a bunch of Delete Data and Insert Data's of the same thing. As in, the data deleted and entered are the same.

When I perform the migration and update the database, the same error happens. I am unsure of how to solve this issue.

The structure of my database is like this:

There are 2 schemas. ManagementStudio.[Name] and DocumentStudio.[Name]

Asp.net core with flutter

$
0
0
how to get asp.net core razor application data from flutter application.please

Proper way to have different menus based on roles

$
0
0

I have the issue that "User.IsInRole" returns false either always, or most of the time, as indicated in this article.

https://stackoverflow.com/questions/53271496/asp-net-core-identity-2-user-isinrole-always-returns-false

Is this link REALLY the way to get the User.IsInRole("admin") to not always return false?   It seems way too cheesy to be the right solution, but I cannot find another.

Here is the relevant code that I have for signing up, which seems to be where the problem may be.

            services.AddDefaultIdentity<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)             
                 .AddRoles<IdentityRole>()
             .AddRoleManager<RoleManager<IdentityRole>>()

                .AddEntityFrameworkStores<ApplicationDbContext>();



.NET Core 2.2 SqlException: Invalid object name 'ApplicationUsers'

$
0
0

I have 2 applications called ManagementStudio and DocumentStudio. I have compiled ManagementStudio into several assemblies that DocumentStudio references.

I use the same Database for both applications but they are separated by different schemas. E.g. ManagementStudio.ApplicationUsers and DocumentStudio.Documents

In DocumentStudio, this is my Startup.cs:

services.AddDbContext<DocumentStudioDbContext>(options => options.UseSqlServer(Environment.GetEnvironmentVariable(DSCASGlobals.DS_ConnectionString)));string assemblyName =typeof(ManagementStudioDbContext).Namespace;
services.AddDbContext<ManagementStudioDbContext>(options =>
    options.UseSqlServer(Environment.GetEnvironmentVariable(DSCASGlobals.DS_ConnectionString),
        optionsBuilder =>
            optionsBuilder.MigrationsAssembly(assemblyName)));
services.AddMvc().AddJsonOptions(options =>{
    options.SerializerSettings.ContractResolver=newNewtonsoft.Json.Serialization.DefaultContractResolver();});var lockoutOptions =newLockoutOptions(){DefaultLockoutTimeSpan=TimeSpan.FromMinutes(5),MaxFailedAccessAttempts=5,};

services.AddDefaultIdentity<ApplicationUsers>(options =>{
    options.Lockout= lockoutOptions;}).AddEntityFrameworkStores<ManagementStudioDbContext>();

DocumentStudio relies on ManagementStudio to login as ManagementStudio contains all the user data and IdentityUser Model.

This is the login on DocumentStudio which is similar to the ManagementStudio one:

privatereadonlySignInManager<ApplicationUsers> _signInManager;privatereadonlyUserManager<ApplicationUsers> _userManager;privatereadonlyApplicationUsersData applicationUsersData;publicLoginModel(SignInManager<ApplicationUsers> signInManager,UserManager<ApplicationUsers> userManager,ApplicationUsersData applicationUsersData){
    _signInManager = signInManager;
    _userManager = userManager;this.applicationUsersData = applicationUsersData;}public async Task<IActionResult>OnPostAsync(string returnUrl =null){var result = await _signInManager.PasswordSignInAsync(Input.UserName,Input.Password,Input.RememberMe, lockoutOnFailure:true);}

However, for some reason, this is the error I get when I try to login:

enter image description here

How can I handle this issue?

Added my ApplicationUsers

publicclassApplicationUsers:IdentityUser{publicstringFirstName{ get;set;}publicstringLastName{ get;set;}[DataType(DataType.Date)][DisplayFormat(DataFormatString="{0:yyyy-MM-dd}",ApplyFormatInEditMode=true)]publicDateTime?DateOfBirth{ get;set;}privateDateTime createdOn =DateTime.Now;publicDateTimeCreatedOn{
        get{return(createdOn ==DateTime.MinValue)?DateTime.Now: createdOn;}set{
            createdOn = value;}}privateDateTime updatedOn =DateTime.Now;publicDateTimeUpdatedOn{
        get{return(updatedOn ==DateTime.MinValue)?DateTime.Now: updatedOn;}set{
            updatedOn = value;}}}

Added my DbContexts

Document Studio

publicDocumentStudioDbContext(DbContextOptions<DocumentStudioDbContext> options):base(options){}publicDbSet<Documents>Documents{ get;set;}publicDbSet<DocumentCategories>DocumentCategories{ get;set;}

ManagementStudio

publicManagementStudioDbContext(DbContextOptions<ManagementStudioDbContext> options):base(options){}publicDbSet<ApplicationUsers>ApplicationUsers{ get;set;}publicDbSet<UserRoles>UserRoles{ get;set;}

Replace route parameters at runtime

$
0
0

What I want is to transform something like: /Home/Reports/1 

to: /Home/Reports/Temps

This article seemed to address it, but I don't understand how to implement this: URL Generation And Slugs In Razor Pages Or MVC

I need to be able to accept an integer Id for a given route, replace the integer with a string representing the name corresponding to the Id, so the URL shown to the user has user-friendly labels instead of Id's. 

.NET Core SqlException: Invalid object name 'IdentityUserClaim'. when logging in

$
0
0

I have 2 applications:

ManagementStudio and DocumentStudio. ManagementStudio consists of several dlls that DocumentStudio references.

When I try to login to DocumentStudio, I get this error:

enter image description here

I'm not sure whats going on because I have included IdentityUserClaim already in the list of my models:

[Table("IdentityUserClaim",Schema="ManagementStudio")]publicclassUserClaims:IdentityUserClaim<string>{[Key]publicoverrideintId{ get;set;}}

enter image description here

publicDbSet<ApplicationUsers>ApplicationUsers{ get;set;}publicDbSet<UserRoles>UserRoles{ get;set;}publicDbSet<UserClaims>UserClaims{ get;set;}publicDbSet<IdentityUserClaim<string>>IdentityUserClaim{ get;set;}publicDbSet<IdentityUserRole<string>>IdentityUserRole{ get;set;}publicDbSet<Applications>Applications{ get;set;}publicDbSet<Roles>Roles{ get;set;}publicDbSet<ApiAccess>ApiAccess{ get;set;}publicDbSet<EventLogs>EventLogs{ get;set;}publicDbSet<ActivityLogs>ActivityLogs{ get;set;}publicDbSet<CommunicationLogs>CommunicationLogs{ get;set;}publicDbSet<UploadLogs>UploadLogs{ get;set;}publicDbSet<Repositories>Repositories{ get;set;}publicDbSet<Emails>Emails{ get;set;}publicDbSet<Assets>Assets{ get;set;}publicDbSet<Announcements>Announcements{ get;set;}publicDbSet<AnnouncementAttachments>AnnouncementAttachments{ get;set;}

I noticed that my CustomClaimsHelper is being called so I'm including it as well:

publicclassCustomClaimsCookieSignInHelper<TIdentityUser>whereTIdentityUser:IdentityUser{privatereadonlySignInManager<TIdentityUser> _signInManager;publicCustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager){
            _signInManager = signInManager;}public async TaskSignInUserAsync(TIdentityUser user,bool isPersistent,IEnumerable<Claim> customClaims){var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);var identity = claimsPrincipal.IdentityasClaimsIdentity;var claims =(from c in claimsPrincipal.Claimsselect c).ToList();var savedClaims = claims;if(customClaims !=null){
                identity.AddClaims(customClaims);}
            await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
                claimsPrincipal,newAuthenticationProperties{IsPersistent= isPersistent });}}

I'm not sure what else I can do to make this work.

EDIT:

I have tested manually creating a table named IdentityUserClaim with the same columns as my ManagementStudio.IdentityUserClaim table and it works. That means if I remove the Schema for IdentityUserClaim, the app will work. However, is there a way to force DocumentStudio to look for the proper Schema?

InvalidOperationException: An error occurred while attempting to establish an SSL or TLS connection.

$
0
0

I get this error message when trying to send email using TFA. 

IEmailSender.cs

 public async Task SendEmailAsync(string email, string subject, string message)
        {
            try
            {
                var mimeMessage = new MimeMessage();

                mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.Sender));

                mimeMessage.To.Add(new MailboxAddress(email));

                mimeMessage.Subject = subject;

                mimeMessage.Body = new TextPart("html")
                {
                    Text = message
                };

                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    if (_env.IsDevelopment())
                    {
                        // The third parameter is useSSL (true if the client should make an SSL-wrapped
                        // connection to the server; otherwise, false).
                        await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, true);
                    }
                    else
                    {
                        await client.ConnectAsync(_emailSettings.MailServer);
                    }

                    // Note: only needed if the SMTP server requires authentication
                    await client.AuthenticateAsync(_emailSettings.Sender, _emailSettings.Password);

                    await client.SendAsync(mimeMessage);

                    await client.DisconnectAsync(true);
                }

            }
            catch (Exception ex)
            {
                // TODO: handle exception
                throw new InvalidOperationException(ex.Message);
            }
        }

Controller

public async Task<IActionResult> SendCode(SendCodeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
            if (user == null)
            {
                return View("Error");
            }

            // Generate the token and send it
            var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
            if (string.IsNullOrWhiteSpace(code))
            {
                return View("Error");
            }

            var message = "Your security code is: " + code;
            if (model.SelectedProvider == "Email")
            {
                await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
            }
            else if (model.SelectedProvider == "Phone")
            {
                await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
            }

            return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
        }


HTTP Error 502.3 - Bad Gateway, Wen deploying asp.net core

$
0
0

I deployed asp.net core website. I have followed all the processes kept online. But I dont know what this particular problem this.

They Application has been previously deployed on 3 other systems and it works fine. So am trying to deploy it on a windows 10 Pc and it giving me a strange error that I have not seen before.

HTTP Error 502.3 - Bad Gateway

<div class="content-container">

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

</div> <div class="content-container">

Most likely causes:

  • The CGI application did not return a valid set of HTTP errors.
  • A server acting as a proxy or gateway was unable to process the request due to an error in a parent gateway.
</div> <div class="content-container">

Things you can try:

  • Use DebugDiag to troubleshoot the CGI application.
  • Determine if a proxy or gateway is responsible for this error.
</div> <div class="content-container">

Detailed Error Information:

<div id="details-left">
Module   AspNetCoreModule
Notification   ExecuteRequestHandler
Handler   aspNetCore
Error Code   0x8007000d
</div> <div id="details-right">
Requested URL   http://localhost:84/
Physical Path   C:\webapplication\POSserver
Logon Method   Anonymous
Logon User   Anonymous
Request Tracing Directory   C:\inetpub\logs\FailedReqLogFiles
<div class="clear"></div> </div>
</div> <div class="content-container">

More Information:

This error occurs when a CGI application does not return a valid set of HTTP headers, or when a proxy or gateway was unable to send the request to a parent gateway. You may need to get a network trace or contact the proxy server administrator, if it is not a CGI problem.

View more information »

SO I CHECK THE EVENT VIEWER TO SEE FOR ERRORS. THE APPLICATION IS NOT LOGGING EVEN THOUGH I ENABLED IT.

An ISAPI reported an unhealthy condition to its worker process. Therefore, the worker process with process id of '10748' serving application pool 'POSServer' has requested a recycle.

Please any idea on what the problem is. I have tried to check  the application from console.

I ran it with dotnet   Application.dll

The application runs and works very well with the IP

localhost:5000

I dont know what to do.

</div>

Extending Identity User with SelectList throwing error

$
0
0

Hi All,

to describe my current situation:

  1. I have several models, inlcuding Operator model with OperatorName property.
  2. I am extending the Identity User via adding Application user and properties. 
  3. I need one of the fields on the registration form to be a drop down of all the operators from db. 
  4. I tried to create property of List<SelectListItems> in the model but when updating-database I get: The entity type 'SelectListGroup' requires a primary key to be defined.

Has anybody got any ideas please?

Thanks.

Logging output customizations for aspnet core app hosted in Azure

$
0
0

I am able to get my aspnet 2.2 application to log to blob storage in Azure with no issue,but I also get a ton of logging from the framework that I would like to throttle/turn down.

At this time, my appsettings.json is simply deployed with the following:

"Logging": {
      "LogLevel": {
      "Default": "Warning"
     }
}

In my Azure "App Service logs" settings, I have Application Logging (Blob) set toInformation
My understanding is:
* The setting in App Service logs would allow events of Information and above to be shown
* The setting in the appsettings file would define that only events of Warning and above would be shown 
* The setting in the appsettings would take precedent and therefore only Warning and above would be logged to the blob

Is my understanding correct?  

Addning nullable value type property to AppUser results null always (even if value set)

$
0
0

I have AppUser class which inherits IdentityUser. While some users will be assigned to relevant company, I've added Company and CompanyId properties to AppUser like below:

 public class AppUser:IdentityUser
    {
        public Company Company { get; set; }
        public int? CompanyId { get; set; }
    }

As you can see, companyId is nullable, but when I register users which wil have their company, it again inserts NULL to the database. Here is the code:

Account controller

 public class AccountController : Controller
    {
        private readonly UserManager<AppUser> _userManager;
        private readonly SignInManager<AppUser> _signInManager;
        private readonly OfferDbContext _offerDbContext;
        private readonly ILogger _logger;

        public AccountController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager, OfferDbContext offerDbContext, ILogger<AccountController> logger)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _offerDbContext = offerDbContext;
            _logger = logger;
        }

Partner company register in account controller

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> RegisterPartner(int Id)
        {
            RegisterModel pvModel = new RegisterModel();
            pvModel.Company = await _offerDbContext.Companies.SingleOrDefaultAsync(a => a.Id == Id);
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> RegisterPartner(RegisterModel registerModel, int Id)
        {

            if (ModelState.IsValid)
            {
                RegisterModel pvModel = new RegisterModel();
                pvModel.Company = await _offerDbContext.Companies.SingleOrDefaultAsync(a => a.Id == Id);

                AppUser partnerUser = await _userManager.FindByEmailAsync(registerModel.Email);

                if(partnerUser != null)
                {
                    ModelState.AddModelError("", "This partner already exists");
                }
                else
                {
                    partnerUser = new AppUser
                    {
                        UserName = registerModel.UserName,
                        Email = registerModel.Email,
                        CompanyId = Id
                    };

                    IdentityResult partnerResult = await _userManager.CreateAsync(partnerUser, registerModel.Password);

                    if (partnerResult.Succeeded)
                    {
                        IdentityResult result = await _userManager.AddToRoleAsync(partnerUser, RoleType.Partner.ToString());

                        if (result.Succeeded)
                        {
                            await _signInManager.SignInAsync(partnerUser, isPersistent: false);
                             _offerDbContext.AppUsers.Add(partnerUser);
                            await _offerDbContext.SaveChangesAsync();
                            return RedirectToAction(nameof(AdminController.Admin), "Admin");
                        }
                    }
                    AddErrors(partnerResult);
                }
            }
            return View(registerModel);
        }

So, after clicking register from companylist view (it's not shown as there is no need) it takes relevant company Id in the "get" action, then creates AppUser for it and saves changes in database in the "post" action.

Register View

@model Foroffer.Models.ViewModels.RegisterModel<section class="posts"><div class="post-container"><div class="row"><div class="col-lg-4 col-md-4 col-sm-6 col-12"></div><div class="col-lg-4 col-md-4 col-sm-6 col-12"><div class="register"><form method="post" asp-action="RegisterAdmin" asp-controller="Account"><div asp-validation-summary="ModelOnly"></div><h6>Qeydiyyat</h6><label asp-for="FullName" style="width: 80px" for="Username">Full Name*</label><input asp-for="FullName" class="loginput" type="text" value=""><br><label asp-for="UserName" style="width: 80px" for="Username">Username*</label><input asp-for="UserName" class="loginput" type="text" value=""><br><span asp-validation-for="UserName"></span><label asp-for="Email" style="width: 80px" for="Email">Email*</label><input asp-for="Email" class="loginput" type="email" value=""><br><span asp-validation-for="Email"></span><label asp-for="Password" style="width: 80px" for="Password">Password*</label><input asp-for="Password" class="loginput" type="text" value=""><span asp-validation-for="Password"></span><button type="submit" class="enter">Göndər</button><br><p><b>Qeyd:</b> Full Name hissədə ad və soyadınızı, Username hissədə yalnız ingilis hərflərilə max 12 simvol, Password hissəsində isə max 14 simvol(tərkibində rəqəm və kiçik hərif mütləqdir) yazılmalıdır.</p></form></div></div><div class="col-lg-4 col-md-4 col-sm-6 col-12"></div></div></div></section>

Why it always adds NULL to the database for companyId property though method assigns companyId to the argument Id in the action?

Render PDF from blob storage in browser

$
0
0

I had this working just fine by converting a PDF to a Base64 string, but Chrome's PDF browser saved downloaded files with the title "download.pdf", and nothing I found could change that. So instead of sending it in as a Base64 string, I thought I could point to the URL of the PDF file and thereby work around the issue with Chrome's default title - if a filename was at the end of the URL, the file downloaded with the correct filename. But I haven't been able to get it to work - at all. Researching it online, I thought I'd be able to handle it via FileStreamResult. Here's that code:

// I don't actually use the filename - it's there only to make
// Chrome use the correct filename. 
public IActionResult GetPdf(Guid guid, string filename)
{
    var blockBlob = BlobStorageMgmt.GetBlobItem(guid);
    blockBlob.FetchAttributes();

    using (MemoryStream ms = new MemoryStream())
    {
        blockBlob.DownloadToStream(ms);

        return new FileStreamResult(ms, "application/pdf");
    }
}

In the view, I have this:

<embed src="@Url.Action("GetPdf", "Home", new { guid = Model.Guid, filename = Model.Filename })" width="100%" height="800" type="application/pdf"></embed>

But all I get is an error message saying "Failed to load PDF document." Please help. 

Viewing all 9386 articles
Browse latest View live


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