Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace WebApiSample.Controllers;

using System.Net.Mime;
using Microsoft.AspNetCore.Mvc;
using WebApiSample.Models;

[ApiController]
[Route("products/actionresultoft")]
public class ActionResultOfTProductsController : ControllerBase
{
private readonly ProductContext _productContext;

public ActionResultOfTProductsController(ProductContext productContext)
{
_productContext = productContext;
}

// <snippet_GetByIdActionResultOfT>
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<Product> GetById_ActionResultOfT(int id)
{
var product = _productContext.Products.Find(id);
return product == null ? NotFound() : product;
}
// </snippet_GetByIdActionResultOfT>

// <snippet_CreateAsyncActionResultOfT>
[HttpPost()]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<Product>> CreateAsync_ActionResultOfT(Product product)
{
if (product.Description.Contains("XYZ Widget"))
{
return BadRequest();
}

_productContext.Products.Add(product);
await _productContext.SaveChangesAsync();

return CreatedAtAction(nameof(GetById_ActionResultOfT), new { id = product.Id }, product);
}
// </snippet_CreateAsyncActionResultOfT>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace WebApiSample.Controllers;

using System.Net.Mime;
using Microsoft.AspNetCore.Mvc;
using WebApiSample.Models;

[ApiController]
[Route("products/iactionresult")]
public class ActionResultProductsController : ControllerBase
{
private readonly ProductContext _productContext;

public ActionResultProductsController(ProductContext productContext)
{
_productContext = productContext;
}

// <snippet_GetByIdIActionResult>
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Product))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetById_IActionResult(int id)
{
var product = _productContext.Products.Find(id);
return product == null ? NotFound() : Ok(product);
}
// </snippet_GetByIdIActionResult>

// <snippet_CreateAsyncIActionResult>
[HttpPost()]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateAsync_IActionResult(Product product)
{
if (product.Description.Contains("XYZ Widget"))
{
return BadRequest();
}

_productContext.Products.Add(product);
await _productContext.SaveChangesAsync();

return CreatedAtAction(nameof(GetById_IActionResult), new { id = product.Id }, product);
}
// </snippet_CreateAsyncIActionResult>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
namespace WebApiSample.Controllers;

using System.Net.Mime;
using Microsoft.AspNetCore.Mvc;
using WebApiSample.Models;

[ApiController]
[Route("products/iresult")]
public class IResultProductsController : ControllerBase
{
private readonly ProductContext _productContext;

public IResultProductsController(ProductContext productContext)
{
_productContext = productContext;
}

// <snippet_GetByIdIResult>
[HttpGet("{id}")]
[ProducesResponseType(typeof(Product), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IResult GetById(int id)
{
var product = _productContext.Products.Find(id);
return product == null ? Results.NotFound() : Results.Ok(product);
}
// </snippet_GetByIdIResult>

// <snippet_CreateAsyncIResult>
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(Product), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IResult> CreateAsync(Product product)
{
if (product.Description.Contains("XYZ Widget"))
{
return Results.BadRequest();
}

_productContext.Products.Add(product);
await _productContext.SaveChangesAsync();

var location = Url.Action(nameof(GetById), new { id = product.Id }) ?? $"/{product.Id}";
return Results.Created(location, product);
}
// </snippet_CreateAsyncIResult>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
namespace WebApiSample.Controllers;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApiSample.Models;

[ApiController]
[Route("[controller]")]
public partial class ProductsController : ControllerBase
Comment thread
brunolins16 marked this conversation as resolved.
{
private readonly ProductContext _productContext;

public ProductsController(ProductContext productContext)
{
_productContext = productContext;
}

// <snippet_Get>
[HttpGet]
public Task<List<Product>> Get() =>
_productContext.Products.OrderBy(p => p.Name).ToListAsync();
// </snippet_Get>

// <snippet_GetOnSaleProducts>
[HttpGet("syncsale")]
public IEnumerable<Product> GetOnSaleProducts()
{
var products = _productContext.Products.OrderBy(p => p.Name).ToList();

foreach (var product in products)
{
if (product.IsOnSale)
{
yield return product;
}
}
}
// </snippet_GetOnSaleProducts>

// <snippet_GetOnSaleProductsAsync>
[HttpGet("asyncsale")]
public async IAsyncEnumerable<Product> GetOnSaleProductsAsync()
{
var products = _productContext.Products.OrderBy(p => p.Name).AsAsyncEnumerable();

await foreach (var product in products)
{
if (product.IsOnSale)
{
yield return product;
}
}
}
// </snippet_GetOnSaleProductsAsync>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
namespace WebApiSample.Controllers;

using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using WebApiSample.Models;

[ApiController]
[Route("products/resultsoft")]
public class ResultsOfTProductsController : ControllerBase
{
private readonly ProductContext _productContext;

public ResultsOfTProductsController(ProductContext productContext)
{
_productContext = productContext;
}

// <snippet_GetByIdResultsOfT>
[HttpGet("{id}")]
public Results<NotFound, Ok<Product>> GetById(int id)
{
var product = _productContext.Products.Find(id);
return product == null ? TypedResults.NotFound() : TypedResults.Ok(product);
}
// </snippet_GetByIdResultsOfT>

// <snippet_CreateAsyncResultsOfT>
[HttpPost]
public async Task<Results<BadRequest, Created<Product>>> CreateAsync(Product product)
{
if (product.Description.Contains("XYZ Widget"))
{
return TypedResults.BadRequest();
}

_productContext.Products.Add(product);
await _productContext.SaveChangesAsync();

var location = Url.Action(nameof(GetById), new { id = product.Id }) ?? $"/{product.Id}";
return TypedResults.Created(location, product);
}
// </snippet_CreateAsyncResultsOfT>
}
18 changes: 18 additions & 0 deletions mvc/action-return-types/7.x/WebApiSample/Models/Product.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace WebApiSample.Models;

using System.ComponentModel.DataAnnotations;

// <snippet_ProductClass>
public class Product
{
public int Id { get; set; }

[Required]
public string Name { get; set; } = string.Empty;

[Required]
public string Description { get; set; } = string.Empty;

public bool IsOnSale { get; set; }
}
// </snippet_ProductClass>
54 changes: 54 additions & 0 deletions mvc/action-return-types/7.x/WebApiSample/ProductContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
namespace WebApiSample;

using Microsoft.EntityFrameworkCore;
using WebApiSample.Models;

public class ProductContext : DbContext
{
public ProductContext(DbContextOptions<ProductContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasData(
new Product
{
Id = 1,
Name = "Learning ASP.NET Core",
Description = "A best-selling book covering the fundamentals of ASP.NET Core",
IsOnSale = true,
},
new Product
{
Id = 2,
Name = "Learning EF Core",
Description = "A best-selling book covering the fundamentals of Entity Framework Core",
IsOnSale = true,
},
new Product
{
Id = 3,
Name = "Learning .NET Standard",
Description = "A best-selling book covering the fundamentals of .NET Standard",
},
new Product
{
Id = 4,
Name = "Learning .NET Core",
Description = "A best-selling book covering the fundamentals of .NET Core",
},
new Product
{
Id = 5,
Name = "Learning C#",
Description = "A best-selling book covering the fundamentals of C#",
}
);

base.OnModelCreating(modelBuilder);
}

public DbSet<Product> Products { get; set; }
}
34 changes: 34 additions & 0 deletions mvc/action-return-types/7.x/WebApiSample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using WebApiSample;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<ProductContext>(opt =>
opt.UseInMemoryDatabase("ProductInventory"));

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;

var context = services.GetRequiredService<ProductContext>();
context.Database.EnsureCreated();
}

app.MapControllers();
app.Run();
15 changes: 15 additions & 0 deletions mvc/action-return-types/7.x/WebApiSample/WebApiSample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.0-rc.1.22427.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.0-rc.1.22426.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions mvc/action-return-types/7.x/WebApiSample/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}