-
Notifications
You must be signed in to change notification settings - Fork 162
New MVC ActionReturnTypes sample project #81
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Rick-Anderson
merged 2 commits into
dotnet:main
from
brunolins16:brunolins16/IResultInMVC
Sep 30, 2022
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
mvc/action-return-types/7.x/WebApiSample/Controllers/ActionResultOfTProductsController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| } |
47 changes: 47 additions & 0 deletions
47
mvc/action-return-types/7.x/WebApiSample/Controllers/ActionResultProductsController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| } |
48 changes: 48 additions & 0 deletions
48
mvc/action-return-types/7.x/WebApiSample/Controllers/IResultProductsController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| } |
55 changes: 55 additions & 0 deletions
55
mvc/action-return-types/7.x/WebApiSample/Controllers/ProductsController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| { | ||
| 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> | ||
| } | ||
43 changes: 43 additions & 0 deletions
43
mvc/action-return-types/7.x/WebApiSample/Controllers/ResultsOfTProductsController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
18
mvc/action-return-types/7.x/WebApiSample/Models/Product.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
54
mvc/action-return-types/7.x/WebApiSample/ProductContext.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
15
mvc/action-return-types/7.x/WebApiSample/WebApiSample.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
8 changes: 8 additions & 0 deletions
8
mvc/action-return-types/7.x/WebApiSample/appsettings.Development.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*" | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.