1

I've been trying to figure this out for about a week now. It's time to ask S.O. I have 4 overall goals here:

  1. The controller code needs to use ViewModel request inputs for validation reasons. (Controller Snippet)
  2. Client code for my API should use a nice model syntax. (Client Code Snippet)
  3. For the swagger UI page, I would like the "Try me" interface to be usable. Either a bunch of text boxes, or a text area for a json blob to serialize and send over.
  4. GET request

Client Code Snippet:

var response = client.GetUserProductHistory(new Models.UserProductHistoryRequest() {
    Locale = "en-US",
    UserPuid = "FooBar"
});

Controller Snippet

    [HttpGet]
    [HasPermission(Permissions.CanViewUserProductHistory)]
    public JsonPayload<UserProductHistoryResponse> GetUserProductHistory([FromUri]UserProductHistoryRequest model)
    {
        JsonPayload<UserProductHistoryResponse> output = new JsonPayload<UserProductHistoryResponse>();
        return output;
    }

I have tried using [FromBody]. It looks great, but I get an error that says 'GET requests do not support FromBody'. I tried using [FromUri], but then the generated client gives me like 15 method parameters per call in the generated client. I tried using [FromUri], and operation filters so that the parameters would be condensed into Ref parameters (complex objects as defined by the spec). This actually worked decently for the client generation and the server side. Problem is, the UI for swagger looks really lame. A single TEXT box that you can't actually use very well. If I can figure out how to get the Swagger UI to change the appearance of the [FromUri] request to more closely match the [FromBody] UI, I will be in good shape here. Any ideas or pre-existing content that would point me in the right direction here?

mason
  • 31,774
  • 10
  • 77
  • 121
Pangamma
  • 731
  • 12
  • 28
  • Wow that's weird. Trying another google session and finding my own question while googling. Hope an actual answer pops up! – Pangamma Sep 01 '18 at 00:13

1 Answers1

2

Swagger is not the limitation - REST itself is. By definition of REST, web servers should ignore the incoming request body on all HTTP GET methods. ASP.NET enforces this convention, which is why you it doesn't allow you to use [FromBody] on the GET method.

When designing a REST API, the better practice is to use POST methods for an actual search. This will allow to use [FromBody], and as a bonus, Swagger will behave the way you want it to. See here for a supporting opinion: https://stackoverflow.com/a/18933902/66101

Dan Ling
  • 2,965
  • 2
  • 29
  • 43
  • Not going to lie, using Post and [FromBody] would make this a LOT easier. Maybe I can convince my team that it is okay to use [HttpPost] for a method that does not create, but rather GETs information. – Pangamma Aug 30 '18 at 21:59