首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将.NET核心3应用程序配置为使用SPA和Swagger?

如何将.NET核心3应用程序配置为使用SPA和Swagger?
EN

Stack Overflow用户
提问于 2020-07-16 12:12:00
回答 1查看 1.3K关注 0票数 0

问题

当我试图在访问SwaggerUI时加载localhost:5001/swagger时,我在SwaggerUI中收到了一个错误,该错误提醒我注意以下情况:

Fetch error undefined /swagger/v1/swagger.json

值得注意的是,我的.NET应用程序在访问SwaggerUI时也会引发错误。

代码语言:javascript
复制
System.OverflowException: Value was either too large or too small for a Decimal.
   at System.Number.ThrowOverflowException(TypeCode type)
   at System.Decimal.DecCalc.VarDecFromR8(Double input, DecCalc& result)
   at System.Decimal.op_Explicit(Double value)
   at NJsonSchema.Generation.JsonSchemaGenerator.ApplyRangeAttribute(JsonSchema schema, IEnumerable`1 parentAttributes)
   at NJsonSchema.Generation.JsonSchemaGenerator.ApplyDataAnnotations(JsonSchema schema, JsonTypeDescription typeDescription)
   at NJsonSchema.Generation.JsonSchemaGenerator.<>c__DisplayClass37_1.<LoadPropertyOrField>b__0(JsonSchemaProperty propertySchema, JsonSchema typeS
chema)
   at NJsonSchema.Generation.JsonSchemaGenerator.GenerateWithReferenceAndNullability[TSchemaType](ContextualType contextualType, Boolean isNullable,
 JsonSchemaResolver schemaResolver, Action`2 transformation)
   at NSwag.Generation.OpenApiSchemaGenerator.GenerateWithReferenceAndNullability[TSchemaType](ContextualType contextualType, Boolean isNullable, Js
onSchemaResolver schemaResolver, Action`2 transformation)
   at NJsonSchema.Generation.JsonSchemaGenerator.LoadPropertyOrField(JsonProperty jsonProperty, ContextualMemberInfo memberInfo, Type parentType, Js
onSchema parentSchema, JsonSchemaResolver schemaResolver)
   at NJsonSchema.Generation.JsonSchemaGenerator.GenerateProperties(Type type, JsonSchema schema, JsonSchemaResolver schemaResolver)
   at NJsonSchema.Generation.JsonSchemaGenerator.GenerateObject(JsonSchema schema, JsonTypeDescription typeDescription, JsonSchemaResolver schemaRes
olver)
   at NSwag.Generation.OpenApiSchemaGenerator.GenerateObject(JsonSchema schema, JsonTypeDescription typeDescription, JsonSchemaResolver schemaResolv
er)
   at NJsonSchema.Generation.JsonSchemaGenerator.Generate[TSchemaType](TSchemaType schema, ContextualType contextualType, JsonSchemaResolver schemaR
esolver)
   at NJsonSchema.Generation.JsonSchemaGenerator.Generate[TSchemaType](ContextualType contextualType, JsonSchemaResolver schemaResolver)
   at NJsonSchema.Generation.JsonSchemaGenerator.GenerateWithReferenceAndNullability[TSchemaType](ContextualType contextualType, Boolean isNullable,
 JsonSchemaResolver schemaResolver, Action`2 transformation)
   at NSwag.Generation.OpenApiSchemaGenerator.GenerateWithReferenceAndNullability[TSchemaType](ContextualType contextualType, Boolean isNullable, Js
onSchemaResolver schemaResolver, Action`2 transformation)
   at NJsonSchema.Generation.JsonSchemaGenerator.GenerateArray[TSchemaType](TSchemaType schema, JsonTypeDescription typeDescription, JsonSchemaResol
ver schemaResolver)
   at NJsonSchema.Generation.JsonSchemaGenerator.Generate[TSchemaType](TSchemaType schema, ContextualType contextualType, JsonSchemaResolver schemaR
esolver)
   at NJsonSchema.Generation.JsonSchemaGenerator.Generate[TSchemaType](ContextualType contextualType, JsonSchemaResolver schemaResolver)
   at NJsonSchema.Generation.JsonSchemaGenerator.GenerateWithReferenceAndNullability[TSchemaType](ContextualType contextualType, Boolean isNullable,
 JsonSchemaResolver schemaResolver, Action`2 transformation)
   at NSwag.Generation.OpenApiSchemaGenerator.GenerateWithReferenceAndNullability[TSchemaType](ContextualType contextualType, Boolean isNullable, Js
onSchemaResolver schemaResolver, Action`2 transformation)
   at NSwag.Generation.AspNetCore.Processors.OperationResponseProcessor.Process(OperationProcessorContext operationProcessorContext)
   at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.RunOperationProcessors(OpenApiDocument document, ApiDescription apiDescription,
 Type controllerType, MethodInfo methodInfo, OpenApiOperationDescription operationDescription, List`1 allOperations, OpenApiDocumentGenerator swagge
rGenerator, OpenApiSchemaResolver schemaResolver)
   at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.AddOperationDescriptionsToDocument(OpenApiDocument document, Type controllerTyp
e, List`1 operations, OpenApiDocumentGenerator swaggerGenerator, OpenApiSchemaResolver schemaResolver)
   at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.GenerateForControllers(OpenApiDocument document, IGrouping`2[] apiGroups, OpenA
piSchemaResolver schemaResolver)
   at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.GenerateAsync(ApiDescriptionGroupCollection apiDescriptionGroups)
   at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.GenerateAsync(Object serviceProvider)
   at NSwag.AspNetCore.OpenApiDocumentProvider.GenerateAsync(String documentName)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.GenerateDocumentAsync(HttpContext context)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.GetDocumentAsync(HttpContext context)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService event
s)
   at IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我想要发生的

我希望能够为我的SwaggerUI提供服务,它记录了为React.js应用程序提供服务的API。

我是如何达到这个问题的

我使用通常在.NET Rider或Visual中找到的“with React.js”模板创建了一个新的JetBrains核心3,并安装/配置了NSwag Nuget。前端(如果不是全部的话)主要由React.js应用程序提供,而.NET web应用程序只是充当API。

Startup.cs

代码语言:javascript
复制
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.EntityFrameworkCore;
using FitnessApplication.Data;
using FitnessApplication.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace FitnessApplication
{
    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.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddControllers().AddJsonOptions(opt =>
            {
                opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; });

            services.AddSwaggerDocument();
        }

        // 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();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/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.UseSpaStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
            
            app.UseOpenApi();
            app.UseSwaggerUi3();
            
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
}

试图补救这个问题

我首先试图纠正这种情况,将对app.UseOpenApi();app.UseSwaggerUi3();的方法调用放在app.UseSpa();调用下面,认为在调用这些方法时出现了某种逻辑错误,但这只会使事情变得更糟,使app.UseSwaggerUi3();完全无法访问。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-16 12:12:00

在阅读了我的.NET应用程序在访问localhost:5001/swagger时提出的错误后,立即发现我的模型或控制器中有什么错误阻止了Swagger规范的生成。原来,当模型属性为double时,我试图在模型属性验证中使用float。

UserStrengthMovement.cs

代码语言:javascript
复制
[Required]
[Range(0, float.MaxValue)]
[DefaultValue(0.0)]
public double WeightKilograms { get; set; }

前面提到的代码块需要更改为:

代码语言:javascript
复制
[Required]
[Range(0, double.MaxValue)]
[DefaultValue(0.0)]
public double WeightKilograms { get; set; }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62934407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档