Search code examples
angularrestasp.net-web-apigetput

Pass a long list of ID's to Web API without putting them in the URL


I'd like to be able to pass a long string (list of ID's) from our Angular front end to our .NET Web API. However, sometimes this string exceeds the URL character limit, so I don't want to pass it via the URL.

What's a good way to do this?

Front end: I first thought to send the string via PUT's HTTP Body in httpOptions, but then I realized with a PUT request, I may not even need HTTP Body - I think I can just pass the data straight into PUT's data parameter.

PUT request

public put(apiPath, data): Observable<any>
{
    var url = this.globals.getBaseUrl() + apiPath + "/" + data["ID"];

    const httpOptions =
    {
        headers: new HttpHeaders({"Content-Type": "application/json"})
        ,withCredentials: true
    };

    return this.httpClient.put<any>(url, data, httpOptions)
        .pipe(catchError(this.handleError));
}  

.

.NET Web API: Then, in the API, how would I dig into this data I've sent via the PUT request? My gameplan was to make a model for this controller that only has one field - the string of ID's. Then in the controller I'd grab it, parse, delimit and pass it to our database. Just unsure how to grab this data in the controller.

Controller:

// PUT: api/myApiPath/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> Put_myTable(int id, _myTable _myTable)
{
    db.Entry(_myTable).State = EntityState.Modified;
        try
        {
            // ----- put -----
            await db.SaveChangesAsync();
            // ----- /put -----
        }
        else
        {
            error = "Unauthorized.";
            throw new HttpResponseException(HttpStatusCode.Forbidden);
        }

}

Solution

  • I'm using .net core, but I think you just need a [FromBody] attribute on your backend parameter something like the below. Whatever object your passing in from the frontend should match the type of object that your backend is expecting. So if you had a simple array of numbers on the frontend your backend would look like the below

    [HttpPut]
    public async Task<IHttpActionResult> Put_myTable([FromBody] List<int> ids)
    {
    }