ASP.NET Core 101 - Enhancing(提高; 增强; ) your Web API: Part 2 [9 of 13]

We got back our products but we didn't actually modify the data or do anything with the data. In this one let's actually change it and write it back into our database.

So what we're going to try to do is make a ratings API that's going to basically go on top of our products service. Now of course this isn't exhaustive.This is not a 300 level Web API video series,so in the future we'll do one of those, but for now we're just getting a taste of what you can do with Web API.

复制代码
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ContosoCrafts.WebSite.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Maker { get; set; }
        
        [JsonPropertyName("img")]
        public string Image { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int[] Ratings { get; set; }

        public override string ToString() => JsonSerializer.Serialize<Product>(this);
    }
}
复制代码

So a rating for us is an array of integers,and noticing ratings isn't currently there.We're probably going to have to write that property again. but right now it's null or it's just not available.

 JsonFileProductService

复制代码
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using ContosoCrafts.WebSite.Models;
using Microsoft.AspNetCore.Hosting;

namespace ContosoCrafts.WebSite.Services
{
   public class JsonFileProductService
    {
        public JsonFileProductService(IWebHostEnvironment webHostEnvironment)
        {
            WebHostEnvironment = webHostEnvironment;
        }

        public IWebHostEnvironment WebHostEnvironment { get; }

        private string JsonFileName
        {
            get { return Path.Combine(WebHostEnvironment.WebRootPath, "data", "products.json"); }
        }

        public IEnumerable<Product> GetProducts()
        {
            using(var jsonFileReader = File.OpenText(JsonFileName))
            {
                return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(),
                    new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
            }
        }

        public void AddRating(string productId, int rating)
        {
            var products = GetProducts();

            if(products.First(x => x.Id == productId).Ratings == null)
            {
                products.First(x => x.Id == productId).Ratings = new int[] { rating };
            }
            else
            {
                var ratings = products.First(x => x.Id == productId).Ratings.ToList();
                ratings.Add(rating);
                products.First(x => x.Id == productId).Ratings = ratings.ToArray();
            }

            using(var outputStream = File.OpenWrite(JsonFileName))
            {
                JsonSerializer.Serialize<IEnumerable<Product>>(
                    new Utf8JsonWriter(outputStream, new JsonWriterOptions
                    {
                        SkipValidation = true,
                        Indented = true
                    }), 
                    products
                );
            }
        }
    }
}
复制代码

So we do a thing called UTF-8 which is the I can speak any language.

ProductsController

We're going to go and get some stuff,and then we were going to call ProductService, just like before.In this case, we're using Get,so we can test it out.But again, for the purposes of what we're doing,but in the future, we might Post,which would make a new thing in the database,or Put, which would update the database,or Patch, which would be like I'm just changing a little.

复制代码
//[HttpPatch] "FromBody
[Route("Rate")]
[HttpGet]
public ActionResult Patch([FromQuery] string productId,[FromQuery] int rating)
{
    ProductService.AddRating(productId, rating);

    return Ok();
}
复制代码

 

posted @   FH1004322  阅读(240)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示