coach_rob
coach_rob

Reputation: 901

How to parse parameters from WebRequest on Callback

OK, I'm working with a third party web API that uses web hooks to communicate when "something happens" on their end. When "something happens" on their end, they send a POST request to my callback URL.

My question is once I catch that POST, how to extract the parameters from it?

I'm attempting to build an integration test scenario where I call my own callback URL with parameters attached so I don't have to go through the "how can I get their callbacks to hit my development machine" routine!

Here is how I'm trying to simulate, but not sure it this is a true representation of what a call to my callback URL might look like:

[Test]
public void {
const string localCallbackUrl = "http://localhost/callback/callbackaction";
HttpWebRequest request = WebRequest.Create(localCallbackUrl) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www.form-urlencoded";
request.Accept = "application/json";

string parameters = string.Format("param1={0}&param2={1}, "foo", "bar");
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

var response = request.GetResponse();
}

The call to "GetResponse()" is hitting my callback URL but I cannot find where the parameters live on the Request object.

NOTE: I am building the request in the same manner that I am building it to make calls to the API, but not 100% sure that is correct.

Upvotes: 0

Views: 2092

Answers (2)

coach_rob
coach_rob

Reputation: 901

With a little digging (post sleep) I found the answer to my question here: How do I post data to MVC Controller using HttpWebRequest?

Apparently the problem was how I was building the request.

Sorry if anyone wasted too much time on answering.

Thank you

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

Simply use the default model binder to parse the parameters and pass them as query string arguments:

[HttpPost]
public ActionResult CallbackAction(string param1, string param2)
{
    ...
}

or if you have many use a view model that contains them as properties:

[HttpPost]
public ActionResult CallbackAction(MyViewModel model)
{
    ...
}

The names of the parameters must match those sent in the POST request body (as per your example param1 and param2).

Upvotes: 2

Related Questions