TAHA SULTAN TEMURI
TAHA SULTAN TEMURI

Reputation: 5291

Post WebApi Method With Parameter C#

I would like to just post Webapi method in asp.net mvc the post action method looks like

  [HttpPost]
    [Route("api/agency/Dashboard")]
    public HttpResponseMessage Index(getCookiesModel cookies)
    {
     //code here
    }

and I am sending post request like this

  string result = webClient.DownloadString("http://localhost:11668/api/agency/dashboard?cookies=" + cookies);

and the getCookiesModel

 public class getCookiesModel
{
    public string userToken { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public long userId { get; set; }
    public string username { get; set; }
    public string country { get; set; }
    public string usercode { get; set; }
}

But this return 404 page not found. Please help me how to solve this.

Upvotes: 0

Views: 62

Answers (1)

Nkosi
Nkosi

Reputation: 247581

DownloadString is a GET request and since the action is expecting a POST, you can see where that may be a problem.

Consider using HttpClient to post the request. If sending the payload in the body then there is no need for the query string, so you also need to update the client calling URL.

var client = new HttpCient { 
    BaseUri = new Uri("http://localhost:11668/")
};

var model = new getCookiesModel() {
    //...populate properties.
};
var url = "api/agency/dashboard";
//send POST request
var response = await client.PostAsJsonAsync(url, model);
//read the content of the response as a string
var responseString = await response.Content.ReadAsStringAsync();

The web API should follow the following syntax

[HttpPost]
[Route("api/agency/Dashboard")]
public IHttpActionResult Index([FromBody]getCookiesModel cookies) {
    //code here...
    return Ok();
}

Upvotes: 2

Related Questions