DayanK
❔ Post Request no working
cs using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ServerLessRestApi
{
public class ProductsGetAllCreate
{
private readonly AppDbContext _context;
public ProductsGetAllCreate (AppDbContext context)
{
_context = context;
}
[FunctionName("ProductsGetAllCreate")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "products")] HttpRequest req)
{
if(req.Method == HttpMethods.Post)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var product = JsonConvert.DeserializeObject<Product>(requestBody);
_context.Products.Add(product);
await _context.SaveChangesAsync();
return new CreatedResult("/products", product);
}
var products = await _context.Products.ToListAsync();
return new OkObjectResult(products);
}
}
}
cs using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ServerLessRestApi
{
public class ProductsGetAllCreate
{
private readonly AppDbContext _context;
public ProductsGetAllCreate (AppDbContext context)
{
_context = context;
}
[FunctionName("ProductsGetAllCreate")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "products")] HttpRequest req)
{
if(req.Method == HttpMethods.Post)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var product = JsonConvert.DeserializeObject<Product>(requestBody);
_context.Products.Add(product);
await _context.SaveChangesAsync();
return new CreatedResult("/products", product);
}
var products = await _context.Products.ToListAsync();
return new OkObjectResult(products);
}
}
}
9 replies