标签: minimal-apis

.NET 6 中使用多个文件的最小 API

在 .NET 6 中,可以创建最少的 API:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products/{id}", (int id) => { return Results.Ok(); })
app.MapGet("/users/{id}", (int id) => { return Results.Ok(); })

app.Run();
Run Code Online (Sandbox Code Playgroud)

将端点分组到多个文件中而不是全部放在程序文件中的方法是什么?

ProductEndpoints.cs:

app.MapGet("/products/{id}", (int id) => { return Results.Ok(); })

UserEndpoints.cs

app.MapGet("/users/{id}", (int id) => { return Results.Ok(); })
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core .net-6.0 minimal-apis

22
推荐指数
3
解决办法
1万
查看次数

MinimalAPI - 您是否打算将“Body(推断)”参数注册为服务或应用 [FromService] 或 [FromBody] 属性?

我创建了一个 asp.net core 空项目,每当我尝试运行我的应用程序时,它都会出现如下错误。当我点击播放时,我什至无法到达终点,它给出了错误。

System.InvalidOperationException HResult=0x80131509 Message=已推断主体,但该方法不允许推断主体参数。以下是我们找到的参数列表:

Parameter           | Source                        
---------------------------------------------------------------------------------
ur                  | Service (Attribute)
userLogin           | Body (Inferred)


Did you mean to register the "Body (Inferred)" parameter(s) as a Service or apply the [FromService] or [FromBody] attribute?
Run Code Online (Sandbox Code Playgroud)

不知道为什么我会收到此错误。然后我尝试添加[FromService],它也显示相同的错误。我针对同一问题阅读了这篇文章,但它说不要添加[Bind]我一开始就没有添加的内容,而是使用[FromService],但我仍然遇到相同的错误。我做错了什么吗?

Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ApplicationDbContext>(x =>
    x.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

builder.Services.AddScoped<IUserRepository, UserRepository>();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapGet("/userLogin", (IUserRepository ur, UserLogin userLogin) =>
{
    return ur.Get(userLogin);
});

if …
Run Code Online (Sandbox Code Playgroud)

http asp.net-core asp.net-core-webapi .net-6.0 minimal-apis

22
推荐指数
2
解决办法
2万
查看次数

将 Swagger 描述添加到最小的 .NET 6 API

我在 .NET 6 中有一个小项目,其中包含类似的最少 API

app.MapGet("/clients",
     async (IClientRepository repo) =>
     {
          var results = await repo.GetClientsAsync();
          return mapper.Map<IEnumerable<ClientModel>>(results);
     });
Run Code Online (Sandbox Code Playgroud)

SwaggerUI我可以使用这个 API,但我找不到向其添加描述的方法(尽管在项目设置中我检查了创建 API XML 文档)。

在此输入图像描述

如何添加 XML 注释?

c# swagger swagger-ui .net-6.0 minimal-apis

17
推荐指数
3
解决办法
2万
查看次数

如何在 .NET 6.0 中使用最小 API 配置 NewtonsoftJson

我有net6.0一个具有最少 api 的项目,我想使用NetwtonsoftJson而不是内置System.Text.Json库来进行序列化和反序列化。

目前我有这个配置JsonOptions并且可以按预期工作

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.SerializerOptions.WriteIndented = true;    
    options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
});
Run Code Online (Sandbox Code Playgroud)

如果我尝试更改为Newtonsoft.Json.JsonSerializerSettings类似下面使用的等效内容,我不会得到相同的行为。相反,它看起来像是使用默认System.Text.Json配置。

builder.Services.Configure<JsonSerializerSettings>(options =>
{
    options.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    options.Converters.Add(
        new StringEnumConverter
        {
            NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy()
        });
});
Run Code Online (Sandbox Code Playgroud)

我知道net5.0我可以用这个

services.AddControllers().AddNewtonsoftJson((options) => //options); // OR
services.AddMvc().AddNewtonsoftJson((options) => //options);
Run Code Online (Sandbox Code Playgroud)

但是,如果我在net6.0项目中像上面那样使用它,那么我就不再使用 MinimalApi 了?

c# json.net asp.net-core .net-6.0 minimal-apis

15
推荐指数
1
解决办法
2万
查看次数

How to access DbContext in .NET 6 minimal API Program.cs

I am trying to call EF Core methods on application startup in my Program.cs file, using the .NET 6 minimal API template and get the following error:

System.InvalidOperationException: 'Cannot resolve scoped service 'Server.Infrastructure.DbContexts.AppDbContext' from root provider.'

// ************** Build Web Application **************

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(configuration.GetConnectionString("AppDb:Postgres")));

// ...

// **************** Web Application *****************

var app = builder.Build();

var dbContext = app.Services.GetService<AppDbContext>(); // error thrown here

if (dbContext != null)
{
    dbContext.Database.EnsureDeleted();
    dbContext.Database.Migrate();
}

// ...
Run Code Online (Sandbox Code Playgroud)

With earlier …

c# entity-framework-core .net-6.0 minimal-apis

14
推荐指数
1
解决办法
2万
查看次数

如何使用 ASP.NET Core 6 最小 api 上传文件?

我想在 ASP.NET Core 6 中创建一个简单的文件上传端点,并认为它会像此处描述的那样简单https://dotnetthoughts.net/handling-file-uploads-in-openapi-with-aspnet-core/

当我定义如下端点时:

app.MapPost("/upload", (IFormFile file) =>
{
    //Do something with the file
    return Results.Ok();
}).Accepts<IFormFile>("multipart/form-data").Produces(200);

Run Code Online (Sandbox Code Playgroud)

当我呼叫端点时,我收到了 415 回复。我收到的消息是这样的:

期望支持 JSON 媒体类型,但得到“multipart/form-data; ...

当我说端点应该接受时,不知道为什么它期望支持的 json multipart/form-data

关于在这里做什么有什么想法或想法吗?

.net asp.net asp.net-core .net-6.0 minimal-apis

12
推荐指数
2
解决办法
2万
查看次数

ASP.NET Minimal API 如何从 URL 返回/下载文件

我正在开发最小的 api,我正在尝试的是当用户访问/download它时立即下载我的图片名为add.png

但无论我尝试什么,它都不起作用,因为我要么得到一个空白页面,只有{}

这可能吗?如果是这样怎么办

这是我迄今为止尝试过的代码。(我对该位置的所有权限都被拒绝访问!)

app.MapGet("/download", async () =>
  {
      var path = "add.png";
      using (var stream = new FileStream(path, FileMode.Open))
      {
          stream.CopyToAsync(stream);
      }
      var ext = Path.GetExtension(path).ToLowerInvariant();
      var result = (ext, Path.GetFileName(path));
      return result;
  });
Run Code Online (Sandbox Code Playgroud)

当用户在我的 api 中执行 /download 并表示他要下载文件时,我该如何执行此操作?

提前致谢

c# asp.net-core-6.0 .net-6.0 c#-10.0 minimal-apis

11
推荐指数
1
解决办法
2万
查看次数

如何在 net 6 和最小 api 中返回内容类型为 json 的 json 字符串?

如果我有一个 json 字符串(例如从文件中读取)并且我的 api 以字符串形式返回,Postman 会将响应视为文本

app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    return json;  
});
Run Code Online (Sandbox Code Playgroud)

那么如何强制内容类型为 application/json 呢?(请不要使用 Newtonsoft)我能够使用该解决方法,但看起来很丑

app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    var jo = JsonSerializer.Deserialize<object>(json);
    return Results.Json(jo);
});
Run Code Online (Sandbox Code Playgroud)

谢谢

c# json asp.net-core minimal-apis

11
推荐指数
1
解决办法
2万
查看次数

.NET 6 最小 API 和多部分/表单数据

使用 .NET 6 Minimal API,我尝试multipart/form-data在 POST 方法中进行处理。但是,使用以下代码:

app.MapPost("/tickets", async (IFreshdeskApiService s, [FromForm] CreateTicketDto dto) => await s.Add(dto))
   .Accepts<CreateTicketDto>("multipart/form-data");
Run Code Online (Sandbox Code Playgroud)

我收到 400 错误请求,正文为:

{
    "error": "Expected a supported JSON media type but got \"multipart/form-data; boundary=--------------------------391539519671819893009831\"."
}
Run Code Online (Sandbox Code Playgroud)

我切换到非最小API(即使用app.MapControllers()),但是有什么方法可以在最小API中处理这个问题吗?

rest multipartform-data asp.net-core .net-6.0 minimal-apis

9
推荐指数
1
解决办法
2万
查看次数

ASP.NET Core 6.0 - 最小 API:Map 方法可使用哪些参数来处理路由?

我是 ASP.NET Core 6.0 中提供的 Minimal API 的新手,根据 Microsoft 的教程(此处此处),可以为 Get 方法定义一个示例路由,如下所示:

app.MapGet("/", () => "Hello World!");
Run Code Online (Sandbox Code Playgroud)

对于Post方法,提供了以下代码:

...
app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todo.Id}", todo);
});
...
Run Code Online (Sandbox Code Playgroud)

在概述的其他部分中,介绍了一些特殊类型,例如:HttpContext, HttpRequest, HttpResponse, ... ,并且它们似乎作为参数注入到路由方法(Get,Post,...);所以所有这些参数都可用:

app.MapPost("/test", (HttpContext context, HttpRequest request, HttpResponse response) => "Hello world!");
Run Code Online (Sandbox Code Playgroud)

我的问题是:这里还有哪些其他可用参数:

app.MapPost("/test", (**HERE???**) => "Hello World!") {};
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core .net-6.0 minimal-apis

7
推荐指数
1
解决办法
1万
查看次数