Search code examples
c#.netvisual-studioasp.net-web-api2odata

how to append an object to a URL


I need to be able to append an encoded object to a URI to pass it to a Web API endpoint.

In this post, the author is creating an object:

var request = new Object();
request.SearchWindowStart = start.toISOString();
request.SearchWindowEnd = end.toISOString();
request.ServiceId = "5f3b6e7f-48c0-e511-80d7-d89d67631c44";
request.Direction = '0';
request.NumberOfResults = 10;
request.UserTimeZoneCode = 1;

Then they are appending it to a URL:

var req = new XMLHttpRequest()
req.open("GET", clientUrl + "/api/data/v8.0/Search(AppointmentRequest=@request)?@request=" + JSON.stringify(request) , true);

I actually cannot modify the C sharp code however I have two options. The first option is to add the parameters into the URL I actually cannot modify the c# code however I have two options. The first option is to add the parameters into the URL and the other option would be to add a body to the request with my intended object.

If I know the structure of the object ahead of time how do I include it with my request?


Solution

  • Based on the code snippet you need to serialize the object to JSON. You can use Json.Net as already linked in the other answer.

    Using OP as an example...

    var request = new {
        SearchWindowStart = "some_start_value",
        SearchWindowEnd = "some_end_value",
        ServiceId = "5f3b6e7f-48c0-e511-80d7-d89d67631c44",
        Direction = '0',
        NumberOfResults = 10,
        UserTimeZoneCode = 1
    };
    //JSON.stringify(request)
    var json = JsonConvert.SerializeObject(request);
    var url = clientUrl + "/api/data/v8.0/Search(AppointmentRequest=@request)?@request=" + json;
    

    From there you should be able to use the URL as desired.