Tal
Tal

Reputation: 544

Test my post api method

I have an api project, with a post method that looks like this:

[Route("api/PostReviewedStudyData")]
[HttpPost]
public bool PostReviewedStudyData(string jsonObject)
{
    //some stuff
    return true;
}

I can't seem to be able to test it I've written a test method like this:

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(@"http://localhost:60604/api/PostReviewedStudyData");

ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Some json parsed object";
byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;

using (Stream stream = httpWReq.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

I get 404 error. Is my Api method not written well, or is my test method does?

Upvotes: 0

Views: 992

Answers (1)

Royi Namir
Royi Namir

Reputation: 148704

There are couple of things :

HttpWebRequest httpWReq =HttpWebRequest)WebRequest.Create(@"http://localhost:60604/api/PostMethod");

ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "=Some json parsed object";
byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;

using (Stream stream = httpWReq.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

Also change the siganture :

public bool PostReviewedStudyData([FromBody] string jsonObject)

Upvotes: 1

Related Questions