【问题标题】:Why is Azure Active Directory Authentication causing an character encoding error in my ASP.NET Core Application?为什么 Azure Active Directory 身份验证会在我的 ASP.NET Core 应用程序中导致字符编码错误?
【发布时间】:2019-11-20 23:15:43
【问题描述】:

我正在制作一个 ASP.NET Core 2.2 应用程序,它使用 KendoUI 作为其框架的一部分。我最近设置了我的应用程序的骨架,然后使用 Visual Studio 2019 的内置向导添加了 Azure Active Directory 身份验证。这为我在 Azure 中创建了一个应用注册,它将根据我公司的活动目录对用户进行身份验证。

问题是,当我现在运行我的应用程序时,我收到以下错误并且没有加载页面:

未声明纯文本文档的字符编码。 该文档将在某些浏览器中呈现乱码 如果文档包含来自外部的字符,则配置 US-ASCII 范围。文件的字符编码需要是 在传输协议或文件中声明需要使用字节顺序 标记为编码签名。

对该消息的进一步调查显示了更多详细信息:

加载此 URI 时出错:协议错误 (unknownError):无法加载 https://localhost:44379/ 的来源。 [异常...“组件 返回失败代码:0x80470002 (NS_BASE_STREAM_CLOSED) [nsIInputStream.available]" nsresult: "0x80470002 (NS_BASE_STREAM_CLOSED)”位置:“JS 框架 :: 资源://devtools/shared/DevToolsUtils.js :: onResponse :: 第 555 行” 数据:无] 堆栈: onResponse@resource://devtools/shared/DevToolsUtils.js:555:34 onStopRequest@resource://gre/modules/NetUtil.jsm:123:17 行:555, 列:0

我查看了在添加 AAD 期间受到影响的所有内容,并且我的项目中的以下文件已更改。

  • appSettings.json
  • Startup.cs
  • 扩展(文件夹)
  • [Authorise] 放在HomeController.cs
  • AzureAD(文件夹)

之前在我的应用程序中使用过 AAD,我希望看到这些文件发生了变化,但之后运行的应用程序从来没有遇到过问题。我开始调查可能导致问题的变化。经过一番工作,我意识到,如果我从控制器中删除 [Authorize],一切都会正常加载。

我猜这可能是我的应用注册的潜在路由问题?我不确定,我需要一些帮助,因为该消息有点像红鲱鱼,因为它表明存在 HTML 格式问题。我需要一些关于出了什么问题的指导。

这是我的代码和项目结构。

结构

我总是将我的 UI 与我的类库分开,因为 AAD 不会更改 Data、Repo 或 Services 库中的文件,为简洁起见,我不会将它们包含在这个问题中。

  • MyCompany.Data
  • MyCompany.Repo
  • MyCompany.Services
  • MyCompany.UI

MyCompany.UI/Controllers/HomeController.cs

using MyCompany.Data;
using Kendo.Mvc.UI;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using MyCompany.Services;
using Kendo.Mvc.Extensions;
using Microsoft.AspNetCore.Authorization;

namespace MyCompany.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly IVesselService _service;

        public HomeController(IVesselService vesselService)
        {
            _service = vesselService;
        }
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult Privacy()
        {
            return View();
        }
        public ActionResult ReadVessels([DataSourceRequest]DataSourceRequest request)
        {
            var vessel = _service.GetVessels();
            return Json(vessel.ToDataSourceResult(request));
        }
        [AcceptVerbs("Post")]
        public ActionResult CreateVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
        {
            if (vessel != null && ModelState.IsValid)
            {
                _service.InsertVessel(vessel);
            }

            return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
        }
        [AcceptVerbs("Post")]
        public ActionResult UpdateVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
        {
            if (vessel != null && ModelState.IsValid)
            {
                _service.UpdateVessel(vessel);
            }

            return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
        }
        [AcceptVerbs("Post")]
        public ActionResult DestroyVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
        {
            if (vessel != null)
            {
                _service.DeleteVessel(vessel.Id);
            }

            return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

MyCompany.UI/Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
using MyCompany.Repo;
using Microsoft.EntityFrameworkCore;
using MyCompany.Services;

namespace MyCompany
{
    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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
               // Maintain property names during serialization. See:
               // https://github.com/aspnet/Announcements/issues/194
               .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            // Database Context
            services.AddDbContext<MyCompanyContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MyCompanyConnection"), b => b.MigrationsAssembly("MyCompany.Repo")));

            //Repository Scope
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
            services.AddTransient<IVesselService, VesselService>();

            //Azure AD Authentication
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));

            //Add KendoUI Services to services container
            services.AddKendo();

            services.AddMvc();
        }

        // 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();
            }
            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.UseCookiePolicy();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

MyCompany/appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ConnectionStrings": {
    "MyCompanyConnection": "Server=tcp:mydatabase.database.windows.net,0000;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=Cloud;Password=Midgar1997!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  },
  "AllowedHosts": "*",
  "AzureAd": {
    "ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "Domain": "mycompany.onmicrosoft.com",
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "xxxxxxxx",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": "xxxxxx",
    "AppIDURL": "https://mycompany.onmicrosoft.com/MyCompany.UI",
    "ConfigView": "MVC"
  }
}

所以,这是与 AAD 直接相关的代码,我不确定这是路由问题还是应用注册配置不正确。我需要一些帮助。

【问题讨论】:

    标签: c# asp.net azure asp.net-core azure-active-directory


    【解决方案1】:

    如果您可以重现此问题,我可以将其作为产品错误报告给 AAD 团队。如果您正在访问其他服务(如 Azure SQL)并且连接存在问题,有时会发生此错误。你有更多的错误日志吗?

    如果您想制作支持票,请随时通过 AzCommunity@microsoft.com 与我联系,我可以为您打开一个案例。

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多