Asp.net mvc 为什么在aspnet core中的IIS上发布时授权失败?

Asp.net mvc 为什么在aspnet core中的IIS上发布时授权失败?,asp.net-mvc,asp.net-core,asp.net-identity,Asp.net Mvc,Asp.net Core,Asp.net Identity,我在我的webapp中使用了aspnet核心身份作为登录功能。我已经在IIS上发布了我的webapp。它可以完美加载,但当我输入用户名和密码并导航到带有authorize属性的操作方法时,应用程序会失败。但是用AllowAnonymous属性重命名动作方法解决了我的问题 注意:当我在本地(localhost)调试应用程序时,该应用程序可以使用authorize属性完美地运行 我怎样才能解决这个问题 startup.cs using Microsoft.Extensions.DependencyI

我在我的webapp中使用了aspnet核心身份作为登录功能。我已经在IIS上发布了我的webapp。它可以完美加载,但当我输入用户名和密码并导航到带有authorize属性的操作方法时,应用程序会失败。但是用AllowAnonymous属性重命名动作方法解决了我的问题

注意:当我在本地(localhost)调试应用程序时,该应用程序可以使用authorize属性完美地运行 我怎样才能解决这个问题

startup.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OnlineExam.Models.LoginModel;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Authorization;
using OnlineExam.Models.CandidateLogin;

namespace OnlineExam
{
    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.AddControllersWithViews();

            services.AddEntityFrameworkSqlServer();
            services.AddIdentity<OnlineExam.Models.UserAccountModel.ApplicationUser, IdentityRole>(options =>
            {
                options.User.AllowedUserNameCharacters = default;
                options.User.RequireUniqueEmail = false;
            })
                    .AddEntityFrameworkStores<Models.UserAccountModel.OnlineExamDBContext>();

            //services.AddMvc();
            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                           .RequireAuthenticatedUser()
                           .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddDbContext<OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<OnlineExam.Models.AdminQuestionModel.OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<CandidateLoginDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<OnlineExam.Models.CandidateExam.CandidateExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddScoped<OnlineExam.Models.UserAccountModel.OnlineExamDBContext>();
            //services.AddScoped<OnlineExam.Controllers.AdminQuestionController>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //    app.UseHsts();
            //}
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

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



using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OnlineExam.Models.UserAccountModel;
using System.Web;
using Newtonsoft.Json;
using System.Text.Json;

namespace OnlineExam.Controllers
{
    [AllowAnonymous]
    public class UserAccountsController : Controller
    {
        private readonly OnlineExamDBContext _context;
        private readonly UserManager<OnlineExam.Models.UserAccountModel.ApplicationUser> _userManager;
        private readonly SignInManager<OnlineExam.Models.UserAccountModel.ApplicationUser> _signInManager;

        List<ApplicationUser> userList = new List<ApplicationUser>();

        public UserAccountsController(OnlineExamDBContext context, UserManager<OnlineExam.Models.UserAccountModel.ApplicationUser> userManager, SignInManager<OnlineExam.Models.UserAccountModel.ApplicationUser> signInManager)
        {
            _context = context;
            _userManager = userManager;
            _signInManager = signInManager;
        }

        // GET: UserAccounts
        public async Task<IActionResult> Index()
        {
            return View(await _context.ApplicationUser.ToListAsync());
        }

        // GET: UserAccounts/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var userAccount = await _context.ApplicationUser
                .FirstOrDefaultAsync(m => m.UserAccountId == id);
            if (userAccount == null)
            {
                return NotFound();
            }

            return View(userAccount);
        }

        // GET: UserAccounts/Create
        [HttpGet]
        public IActionResult Create()
        {
            var viewmodel = new ApplicationUser();
            return View(viewmodel);
        }

        // POST: UserAccounts/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(ApplicationUser userModel)
        {
            if (ModelState.IsValid)
            {
                bool userCheck = IsUserExists(userModel.UserName);
                if (userCheck == false)
                {
                    var user = new OnlineExam.Models.UserAccountModel.ApplicationUser();
                    user = userModel;
                    var result = await _userManager.CreateAsync(user, userModel.UserPassword);
                    if (result.Succeeded)
                    {
                        return Logout();
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("","Username already exist");
                }

            }
            return View(userModel);
        }

        // GET: UserAccounts/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var userAccount = await _context.ApplicationUser.FindAsync(id);
            if (userAccount == null)
            {
                return NotFound();
            }
            return View(userAccount);
        }

        // POST: UserAccounts/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("UserAccountId,UserName,UserPassword,UserFullName,UserGender,UserPriviledge,UserDesignation,UserDepartment,UserMailId,UserAddress,UserMobileNo,UserPhoto,UserQualification")] UserAccount userAccount)
        {
            if (id != userAccount.UserAccountId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userAccount);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserAccountExists(userAccount.UserAccountId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(userAccount);
        }

        // GET: UserAccounts/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var userAccount = await _context.ApplicationUser
                .FirstOrDefaultAsync(m => m.UserAccountId == id);
            if (userAccount == null)
            {
                return NotFound();
            }

            return View(userAccount);
        }

        // POST: UserAccounts/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var userAccount = await _context.ApplicationUser.FindAsync(id);
            _context.ApplicationUser.Remove(userAccount);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool UserAccountExists(int id)
        {
            return _context.ApplicationUser.Any(e => e.UserAccountId == id);
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(ApplicationUser login)
        {
            ///var user = new OnlineExam.Models.UserAccountModel.ApplicationUser { UserName = login.UserName };
            //TempData["user"] = user;
            var result = await _signInManager.PasswordSignInAsync(login.UserName, login.UserPassword, true, false);

            if (result.Succeeded)
            {
                 var userData = from x in _context.ApplicationUser.Where(x => x.UserName == login.UserName).ToList()
                                    select new { x.UserFullName, x.Email, x.UserAddress ,x.UserName
                                    ,x.UserPhoto ,x.UserMobileNo,x.UserGender,x.UserQualification,
                                    x.UserDepartment,x.UserDesignation,x.UserPriviledge,x.UserAccountId};

                //List<ApplicationUser> userList = new List<ApplicationUser>();
                foreach (var item in userData)
                {
                    userList.Add(new ApplicationUser 
                    { UserFullName =item.UserFullName, UserAccountId= item.UserAccountId,UserName=item.UserName,
                      Email=item.Email,UserDepartment=item.UserDepartment,UserGender=item.UserGender, 
                      UserPriviledge=item.UserPriviledge, UserPhoto=item.UserPhoto, UserAddress=item.UserAddress
                    });
                    //userList.Add(new ApplicationUserReplica { UserAccountId = item.UserAccountId });
                }
                //List<ApplicationUserReplica> userList= new List<ApplicationUserReplica>();
                //userList.Add(new ApplicationUserReplica { UserFullName = userData.Select(x => x.UserFullName).ToString()});
                // userList.Add(new ApplicationUserReplica { UserAccountId =Convert.ToInt32(userData.Select(x => x.UserAccountId)) });

                var sdata=JsonConvert.SerializeObject(userList);
                TempData["userData"] = sdata;
                return RedirectToAction(nameof(LoginInfo));
            }
            else
            {
                ModelState.AddModelError("", "Please enter you username and password correctly");
            }
            return View(login);
        }
        public  bool IsUserExists(string userName)
        {
            int c=_context.ApplicationUser.Where(x => x.UserName == userName).Count();
            if (c >= 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        [AllowAnonymous]
        public ActionResult Logout()
        {
            _signInManager.SignOutAsync();
            return RedirectToAction(nameof(Login));
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult LoginInfo()
        {
            userList=JsonConvert.DeserializeObject<List<ApplicationUser>>(TempData["userData"].ToString());
            TempData.Keep();
            foreach(var item in userList)
            {
                TempData["userId"] = item.UserAccountId;
            }
            return View();
        }
    }
}
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用OnlineExam.Models.LoginModel;
使用Microsoft.EntityFrameworkCore.Infrastructure;
使用Microsoft.AspNetCore.Identity;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Mvc.Filters;
使用Microsoft.AspNetCore.Mvc.Authorization;
使用OnlineExam.Models.CandidateLogin;
名称空间在线考试
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
//services.AddControllersWithViews();
services.AddEntityFrameworkSqlServer();
服务.附加性(选项=>
{
options.User.AllowedUserNameCharacters=默认值;
options.User.RequireUniqueEmail=false;
})
.AddEntityFrameworkStores();
//services.AddMvc();
services.AddMvc(选项=>
{
var policy=new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()文件
.Build();
options.Filters.Add(新的授权过滤器(策略));
});
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“LoginConnection”));
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“LoginConnection”));
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“LoginConnection”));
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“LoginConnection”));
services.addScope();
//services.addScope();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
//if(env.IsDevelopment())
//{
//app.UseDeveloperExceptionPage();
//}
//否则
//{
//app.UseExceptionHandler(“/Home/Error”);
////默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
//app.UseHsts();
//}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Index}/{id?}”);
});
}
}
}
使用System.Collections.Generic;
使用System.Linq;
使用System.Security.Claims;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Identity;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.AspNetCore.Mvc.Rendering;
使用Microsoft.EntityFrameworkCore;
使用OnlineExam.Models.UserAccountModel;
使用System.Web;
使用Newtonsoft.Json;
使用System.Text.Json;
命名空间OnlineExam.Controllers
{
[异名]
公共类UserAccountsController:控制器
{
私有只读联机ExamdbContext\u上下文;
私有只读用户管理器_UserManager;
专用只读签名管理器\u签名管理器;
List userList=新列表();
公共用户帐户控制器(OnlineExamDBContext上下文、UserManager用户管理器、SignInManager SignInManager)
{
_上下文=上下文;
_userManager=userManager;
_signInManager=signInManager;
}
//获取:用户帐户
公共异步任务索引()
{
返回视图(wait_context.ApplicationUser.ToListAsync());
}
//获取:UserAccounts/Details/5
公共异步任务详细信息(int?id)
{
if(id==null)
{
返回NotFound();
}
var userAccount=await\u context.ApplicationUser
.FirstOrDefaultAsync(m=>m.UserAccountId==id);
if(userAccount==null)
{
返回NotFound();
}
返回视图(用户帐户);
}
//获取:UserAccounts/Create
[HttpGet]
public IActionResult Create()
{
var viewmodel=newapplicationuser();
返回视图(viewmodel);
}
//POST:UserAccounts/Create
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务创建(ApplicationUser用户模型)
{
if(ModelState.IsValid)
{
bool userCheck=IsUserExists(userModel.UserName);
if(userCheck==false)
{
var user=new OnlineExam.Models.UserAcc