是否可以向 dotnetcore api 应用程序中的路径变量添加参数验证?

问题描述 投票:0回答:1

给出方法:

/// <param name="containername">The container the file resides in.</param>
/// <param name="fileName">The name of the file to get.</param>
/// <returns>The file specified.</returns>
[HttpGet("{containername}/contentfiles/{fileName}", Name = "Get")]
[ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status503ServiceUnavailable)]
public ActionResult Get(string containername, string fileName)

我检查容器名称和文件名对于我的目的是否有效,然后获取数据。

Swagger 自动给我 *required,但不是最小长度和最大长度,这是有道理的,因为它不知道在哪里可以找到这些。

我希望我能做这样的事情:

/// <param name="containername" minimum="3" maximum="63">The container the file resides in.</param>

但它只是放弃了那些。如何将它们添加到我自动生成的 Swagger 文档中(我正在使用 Swashbuckle,以防万一)?

c# asp.net-core swagger swashbuckle
1个回答
3
投票

我使用 ASP.NET Core 3.1 Api 项目创建了一个示例项目。

首先让我们看一下控制器,注意 ApiController 属性,并注意 FromRoute 属性:

    using Microsoft.AspNetCore.Mvc;
    using System.ComponentModel.DataAnnotations;

    namespace ValidationExampleApi.Controllers
    {
      [ApiController]
      [Route("[controller]")]
      public class ValidationController : ControllerBase
      {
        [HttpGet("{containername}/contentfiles/{fileName}")]
        public bool Get([FromRoute]RequestModel request)//it will return 400 bad request if validation fails
        {
          if(ModelState.IsValid)//please note in this case this line will never be hit.
          {
            return false;
          }
          else
          {
            return true;
          }
        }
      }

    }

现在让我们看一下模型并注意带有一些验证规范的数据注释:

    using Microsoft.AspNetCore.Mvc;
    using System.ComponentModel.DataAnnotations;

    namespace ValidationExampleApi.Controllers
    { 
      public class RequestModel
      {
        [Required(AllowEmptyStrings = false)]
        [StringLength(5, MinimumLength = 2)]
        public string containername { get; set; }

        [Required(AllowEmptyStrings = false)]
        [StringLength(5, MinimumLength = 2)]
        public string fileName { get; set; }
      }
    }

现在让我们看看我的启动类,注意我添加了普通的默认 swashbuckle 配置:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace ValidationExampleApi
{
  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.AddControllers();
      services.AddSwaggerGen(c =>
      {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
      });
    }

    // 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();
      }

      // Enable middleware to serve generated Swagger as a JSON endpoint.
      app.UseSwagger();

      // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
      // specifying the Swagger JSON endpoint.
      app.UseSwaggerUI(c =>
      {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.RoutePrefix = string.Empty;
      });

      app.UseRouting();

      app.UseAuthorization();

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

现在看看我的招摇如何表明我违反了最大长度:

最后注意事项:

您还可以将路由参数与查询参数结合起来。 您还可以在模型的属性级别应用“FromRoute”属性。 有很多方法可以做到这一点。这只是一个“让您开始”的示例。

自定义错误响应:

在这里您可以看到如何使用错误处理程序以及 InvalidModelStateFactory 和 ValidationProblemDetails:自定义处理错误

这是有关如何使用 InvalidModelStateFactory 的另一个示例: 关于如何自定义错误的另一个示例

© www.soinside.com 2019 - 2024. All rights reserved.