Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - 如何在JSON中编写POST请求以发布新产品?(How do I write a POST request in JSON to post a new product?)

I am working on a WebAPI.

(我正在使用WebAPI。)

I have used Entity framework to make an SQL database via the C# code my friend and I have written.

(我已经使用实体框架通过我的朋友和我编写的C#代码创建SQL数据库。)

Our product table in the SQL Database is based on the following code:

(我们在SQL数据库中的产品表基于以下代码:)

public class Product
{

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Display(Name = "Product Number")]
    public int ProductID { get; set; }
    [StringLength(50, MinimumLength = 3)]
    public string ProductName { get; set; }


    [Range(0, 99999)]
    public int Price { get; set; }

    public int MarketID { get; set; }


    public Market Market { get; set; }    
    public ICollection<Subscription> Subscriptions { get; set; }
    public ICollection<ProductAssignment> ProductAssignments { get; set; }

}

When we run our solution and open up Postman to make a post request we are not sure how the JSON should be written.

(当我们运行解决方案并打开Postman进行发布请求时,我们不确定JSON的编写方式。)

So far we have written:

(到目前为止,我们已经写了:)

{
"ProductID": 1234,
  "ProductName": "Testproduct",
  "Price": 10,
  "MarketID": 4321,
  "Market": 
    {
       "MarketID": 1111,
       "Name": "Market1",
       "Budget": 1.5,
       "StartDate": 2019-11-28,
       "ProductGuideID": 123
    }
    "Subscriptions":
    {
        "SubscriptionId":1234,
        "ProductId": 1234,
        "CustomerID": 1234,
        "CustomerLoyalty": "A"
    }
    "ProductAssignments"
    {
        "ProductGuideId": 1234,
        "ProductID": 1234
    }
}

The problem is that we do not know how to write the JSON for Market, Subscriptions and ProductAssignments.

(问题是我们不知道如何为市场,订阅和产品分配编写JSON。)

What should we write in JSON to POST a new Product?

(我们应该用JSON写什么来发布新产品?)

EDIT:

(编辑:)

Market class:

(市场类别:)

public class Market
    {
        public int MarketID { get; set; }

        [StringLength(50, MinimumLength = 3)]
        public string Name { get; set; }

        [DataType(DataType.Currency)]
        [Column(TypeName = "money")]
        public decimal Budget { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Start Date")]
        public DateTime StartDate { get; set; }

        public int? ProductGuideID { get; set; }

        [Timestamp]
        public byte[] RowVersion { get; set; }

        public ProductGuide Administrator { get; set; }
        public ICollection<Product> Products { get; set; }
    }

Subscription:

(订阅:)

 public enum CustomerLoyalty
{
    A, B, C, D, F
}
public class Subscription
{
    public int SubscriptionID { get; set; }
    public int ProductID { get; set; }
    public int CustomerID { get; set; }
    [DisplayFormat(NullDisplayText = "Loyalty not set")]
    public CustomerLoyalty? CustomerLoyalty { get; set; }

    public Product Product { get; set; }
    public Customer Customer { get; set; }
}

ProductAssignment:

(产品分配:)

public class ProductAssignment
{
    public int ProductGuideID { get; set; }
    public int ProductID { get; set; }
    public ProductGuide ProductGuide { get; set; }
    public Product Product { get; set; }
}

EDIT: ProductsController.cs:

(编辑:ProductsController.cs:)

namespace VitekAPI.Controllers
{
    [Route("api/Products")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly BusinessContext _context;

    public ProductsController(BusinessContext context)
    {
        _context = context;
    }

    // GET: api/Products
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
    {
        return await _context.Products.ToListAsync();
    }

    // GET: api/Products/5
    [HttpGet("{id}")]
    public async Task<ActionResult<Product>> GetProduct(int id)
    {
        var product = await _context.Products.FindAsync(id);

        if (product == null)
        {
            return NotFound();
        }

        return product;
    }

    // PUT: api/Products/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see https://aka.ms/RazorPagesCRUD.
    [HttpPut("{id}")]
    public async Task<IActionResult> PutProduct(int id, Product product)
    {
        if (id != product.ProductID)
        {
            return BadRequest();
        }

        _context.Entry(product).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProductExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Products
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see https://aka.ms/RazorPagesCRUD.
    [HttpPost]
    public async Task<ActionResult<Product>> PostProduct(Product product)
    {
        _context.Products.Add(product);
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (ProductExists(product.ProductID))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtAction("GetProduct", new { id = product.ProductID }, product);
    }

    // DELETE: api/Products/5
    [HttpDelete("{id}")]
    public async Task<ActionResult<Product>> DeleteProduct(int id)
    {
        var product = await _context.Products.FindAsync(id);
        if (product == null)
        {
            return NotFound();
        }

        _context.Products.Remove(product);
        await _context.SaveChangesAsync();

        return product;
    }

    private bool ProductExists(int id)
    {
        return _context.Products.Any(e => e.ProductID == id);
    }
}

EDIT: Link to our github repository: https://github.com/tux-superman/VitekSky

(编辑:链接到我们的github存储库: https : //github.com/tux-superman/VitekSky)

  ask by CodingStudent translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can lookup the notations of JSON types here .

(您可以在此处查找JSON类型的符号。)

Given your product class the JSON Notation would look something like this:

(给定您的产品类,JSON表示法如下所示:)

{
  "ProductID": 1234,
  "ProductName": "Testproduct",
  "Price": 10,
  "MarketID": 4321,
  "Market": 
    {
       "MarketID": 1111,
       "Name": "Market1",
       "Budget": 1.5,
       "StartDate": 2019-11-28,
       "ProductGuideID": 123
    }
    // All your other custom objects
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...