ASP.NET MVC Project: RESTful API method with compl

2019-08-02 05:28发布

问题:

I am new to designing API's, and I have a situation in ASP.NET MVC.

In my domain system, I have different concepts, such as an Invoice. I want to create a REST API, where it is possible to:

  • Create
  • Update
  • Delete
  • Select (based on different elements)

But, for instance, when creating a new object, I need a big set of parameters (see an example viewmodel below).

If I expect a path such as this:

POST - /api/invoice/create

How would I go around and accept form data?

My best guess is to make an APIController, and then accept the InvoiceViewModel as the only parameter. As it is an API Controller, I assume it accepts JSON by default.

Then I have the following question(s):

  • In jQuery, how would I build a JSON object to "satisfy" this InvoiceViewModel?
  • Is this the best way to handle more complex products?

InvoiceViewModel:

 public class InvoiceViewModel
    {
        public int Id { get; set; }

        public string Comment { get; set; }

        public InvoiceAddressViewModel CompanyInfo { get; set; }
        public InvoiceAddressViewModel ReceiverInfo { get; set; }

        public DateTime DateCreated { get; set; }

        public List<InvoiceLineViewModel> Lines { get; set; }

        public decimal Total { get; set; }
        public decimal VatTotal { get; set; }
        public decimal VatPercentage { get; set; }
        public decimal TotalExVat { get; set; }

        public InvoiceViewModel()
        {
            this.Lines = new List<InvoiceLineViewModel>();
        }
    }

    public class InvoiceAddressViewModel
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Company { get; set; }
        public string VatNumber { get; set; }
        public string Country { get; set; }
        public string ZipCode { get; set; }
        public string City { get; set; }
    }

    public class InvoiceLineViewModel
    {
        public string Title { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
    }

回答1:

There is a default JsonValueProviderFactory for the Asp.net-mvc 3 framework, as long as your JSON data posted to the Action matches the Model it should bind the data correctly.

So something like this:

  var requestData = {
    Id: "1",
    Comment: "The quick brown fox",
    CompanyInfo: {
        Name: "etc."
    }
  };

  $.ajax({
     url: '/api/invoice/create',
     type: 'POST',
     data: JSON.stringify(requestData),
     dataType: 'json',
     contentType: 'application/json; charset=utf-8',
     error: function (xhr) {
        alert('Error: ' + xhr.statusText);
     },
     success: function (result) {
        alert('success');
     }
  });

Should work just fine, all the data should be bound correctly, just match the JSON property names with the Model names.(they must match)

The best way to get your model to match is to simply serialize your Model in your view to JSON, then you know it is correct, and manipulate it to your hearts content.

var data = set(@Html.Raw(new JavaScriptSerializer().Serialize(Model)));

As for complexity, the sky is the limit you may (very unlikely) run into some scenarios where the default JsonValueProviderFactory for .net is not good enough, but if you do I would be suprised.

Just as a side note, this whole use-case works wonderfully with http://knockoutjs.com/.

Have fun.