【问题标题】:DevExpress routing appears to break with dotnet core 3.1DevExpress 路由似乎与 dotnet core 3.1 中断
【发布时间】:2021-01-09 14:10:55
【问题描述】:

我的dotnet core webapp index.cshtml 页面中有以下DxDatagrid 块:

@(Html.DevExtreme().DataGrid<UserModel>()
    .ID("grid-container")
    .ShowBorders(true)
    .DataSource(d => d.Mvc().Controller("UserSearch").LoadAction("Get").Key("UserId"))
    .Selection(s => s
        .Mode(SelectionMode.Multiple)
        .SelectAllMode(SelectAllMode.Page)
        )

使用此代码并使用dotnet core 2.2,数据源会调用:

http://localhost:5000/api/UserSearch/Get?skip=0&take=10&requireTotalCount=true&_=1600859370033

更新到 dotnet core 3.1 并更新了 csproj_Layout.cshtml 文件中的 DevExpress 引用,路由现在尝试调用:

http://localhost:5000/?skip=0&take=10&requireTotalCount=true&_=1600859693687

startup.cs 是这样的:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AccessUsers.Middleware;
using AccessUsers.Models;
using Microsoft.AspNetCore.HttpOverrides;

namespace WebAppTest
{
    public class Startup
    {
        private readonly IConfiguration _config;
        private readonly AppSettings _appSettings;

        public Startup(IConfiguration config)
        {
            _config = config;
            _appSettings = _config.Get<AppSettings>();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        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 => false;
                // options.MinimumSameSitePolicy = SameSiteMode.None;

                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie = cookieContext => cookieContext.CookieOptions.SameSite = SameSiteMode.Unspecified;
                options.OnDeleteCookie = cookieContext => cookieContext.CookieOptions.SameSite = SameSiteMode.Unspecified;
            });

            services.Configure<AppSettings>(_config);

            services.AddSingleton<APIService>();
            services.AddSingleton<UserService>();
            services.AddSingleton<ShipToService>();

            services.AddApplicationInsightsTelemetry();

            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddSession();
            services.AddMemoryCache();
            
            services.AddRazorPages().AddNewtonsoftJson(options => {
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            }).AddXmlSerializerFormatters();

            services.UseOpenIDConnectMiddleware(new OpenIDConnectMiddlewareOptions
            {
                BaseUrl = _appSettings.API.BaseUrl,
                AppName = _appSettings.AppName,
                ClientId = _appSettings.API.ClientId,
                ClientSecret = _appSettings.API.ClientSecret,
                Secure = !_appSettings.Local
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedProto
            });

            if (_appSettings.Local)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
                app.UseGlobalLoginMiddleware();
                app.UseHttpsRedirection();
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseSession();

            app.UseEndpoints(endpoints => {
                endpoints.MapRazorPages();
            });

            CultureInfo[] allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
            string location = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            var supportedCultures = allCultures.Where(c => Directory.Exists(Path.Combine(location, c.Name)) && c.LCID != 127).ToList();

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-US"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });
        }
    }
}

csproj 包含以下内容:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
  </PropertyGroup>


  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.6" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.7" />
    <PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="6.7.1" />

    <PackageReference Include="DevExtreme.AspNet.Data" Version="2.7.1" />
    <PackageReference Include="DevExtreme.AspNet.Core" Version="20.1.7" />

    <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.7.1" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.7.1" />

    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.14.0" />

    <PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="5.0.0" />
  </ItemGroup>

</Project>

controller.cs 包含以下内容:

using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using AccessUsers.Models;
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace WebAppTest.Pages
{
    [Route("api/[controller]/[action]")]
    public class UserSearchController : Controller
    {
        private readonly UserService _userService;

        public UserSearchController(UserService userService)
        {
            _userService = userService;
        }

        [HttpGet]
        public object Get(DataSourceLoadOptions loadOptions)
        {
            var result =  DataSourceLoader.Load(GetProfiles(user:new UserModel(),useDummyData: true), loadOptions);

            return result;
        }

_Layout.cshtml 包含以下内容:

<script src="https://cdn3.devexpress.com/jslib/20.1.7/js/dx.all.js" integrity="sha384-LAn+t9UxSqkm8biNuoUbJcohKoYmbiFRfVLERIJ4I3RyEpAIBizEcIztuXPG9Cqg sha512-OAjfsw+eXv345AD9H6kDJLChXetpJD6ChGgDvjVIEumiHYulOLXIO/Do5gxljW2GUgpObic42JyS8a0wZqb1Fw==" crossorigin="anonymous"></script>
<script src="https://cdn3.devexpress.com/jslib/20.1.7/js/dx.aspnet.mvc.js" integrity="sha384-5rtF4jUX5Hez5YwkW7PHC/0XplJQS26qVUCfec8fBX0IkoR1y35EXHkZDbgeMh3x sha512-0eJebJTnN45FCtUOrVqxk5p73OMWsx94vLQpnlRtDp/CKbssiUR0j0os+0y01fvzDtdtnEKSeau32g30fgtrYQ==" crossorigin="anonymous"></script>

这里指定: https://js.devexpress.com/Documentation/Guide/Common/Distribution_Channels/CDN/

我确定是对 dotnet core 3.1 的更改导致路由中断,因为应用程序的功能没有改变,但我看不出具体是什么中断了它。

【问题讨论】:

  • 您使用的是哪个 DxDatagrid 版本? .NET Core 3.x 是一个主要版本。 预计会有重大变化。为旧版本构建的第三方库可能存在问题,或者您可能不再使用 MVC 控制器。顺便说一句,您没有发布代码中最重要的部分,即控制器。这与路由无关,它是网格助手生成 URL 的方式
  • d.Mvc().Controller("UserSearch").LoadAction("Get") 负责使用 reflection 和指定为字符串的名称生成/api/UserSearch/Get?。如果名称错误,在意外的命名空间中或使用意外的基类,则该调用链很容易失败。您的配置中没有 AddMvc(),因此 d.Mvc() 可能从一开始就失败
  • 我已经用控制器 sn-p 更新了我的帖子。
  • 如何找到我正在使用的数据网格的版本号?我假设它是 20.1.7,因为那是 DevExpress 包版本。
  • 你能直接调用那个控制器吗?您的 Startup 中没有 AddMvc()AddControllers(),只有 AddRazorPages()

标签: .net-core devexpress-gridcontrol


【解决方案1】:

Startup.ConfigureServices 不添加对控制器的支持,仅适用于具有以下功能的 Razor 页面:

services.AddRazorPages().AddNewtonsoftJson(options => {
        ...
        }).AddXmlSerializerFormatters();

来自Remarks in the method's documentation

该方法为页面常用功能配置MVC服务。

要为 API 的控制器添加服务,请调用 AddControllers(IServiceCollection)。

控制器现在从未注册,因此尝试生成操作 URL 的代码

.DataSource(d => d.Mvc().Controller("UserSearch").LoadAction("Get")

找不到任何东西并返回一个空字符串。

要解决此问题,请添加控制器支持:

services.AddControllers().AddNewtonsoftJson(options => {
        ...
        }).AddXmlSerializerFormatters();
services.AddRazorPages();

控制器也应该添加到Configure 的端点路由代码中,MapControllers

app.UseEndpoints(endpoints => {
    endpoints.MapRazorPages();
    endpoints.MapControllers();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2020-10-13
    • 2021-01-29
    • 2021-06-25
    • 2020-11-15
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多