How do I use WebAPI/Rest correctly when other para

2019-06-14 04:15发布

问题:

I am new to WebAPI and rest and am trying to do things correctly. By default if I were to access something such as User I would call api/user/5 if I wanted user 5. This would go to my User controller to Get(int num) I think. But I know I will often need other params passed as well. Currently I have Get(JObject data), but that data param is for other parameters. I will need other optional params whether I am sending an ID or wanting a list of everything. How do I go about organizing methods properly with WebAPI? Am I misunderstanding something?

To clarify: This question is more about REST than dynamic objects, though they play a part:

How do I get a single resource vs a list of resources when I need additional params. I see those concepts as two separate methods, but the additional params complicate it in my mind when routing is involved.

回答1:

Use attribute routing

For example -

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

or

[Route("customers/{customerId}/orders/{orderId}")]
public Order GetOrderByCustomer(int customerId, int orderId) { ... }

if you need to return a list, create a method that returns a list, otherwise return the specific item requested



回答2:

Look into using JToken or the even more dynamic 'dynamic' (Taken from here)

" JSON and JavaScript is really dynamic, though, and often it's a hassle to try to "deserialize" really dynamic JSON objects into strongly-typed .NET structures. JSON.NET and ASP.NET Web API's model binding offer a happy medium - a middle ground - called JToken.

public class ContactController : ApiController
{
    public JToken Post(JToken contact)
    {
        return contact;
    }
}

Using JToken gives a dynamic container but also a DOM-like navigation model. But if that's not dynamic enough for me, why can't my method's parameter just take a "dynamic."

C# is statically typed, sure, but that doesn't mean I can't statically type something dynamic. ;)

Again, note the watch window.

Using dynamic to catch JSON post payloads

public class ContactController : ApiController
{
    public dynamic Post(dynamic contact)
    {
        return contact;
    }
}

"



回答3:

I think you should make a new object for each WebAPI function that will handle the request. You can make the parameters optional with nullable properties.

[HttpPost]
public void SampleFunction(SampleFunctionModel model)
{

}

where SampleFunctionModel is:

public class SampleFunctionModel
{
    public int? Id { get; set; }

    public string Name { get; set; }
}