1

I just started playing around with RestSharp and WebApi and I've run into a little bit of an issue.

I'm not sure if this is best practice or even possible, but I'll demonstrate through code (this isn't my exact code but it's the exact same concept)

    [HttpPost]
    public HttpResponseMessage CreateEmployee(Employee emp, int employeeType)
    {
        // CREATE EMPLOYEE
        return Request.CreateResponse(HttpStatusCode.Created, emp.id);
    }

I've created a console app to test this using RestSharp. Here's what I have:

        var client = new RestClient();
        client.BaseUrl = @"http://localhost:15507";

        var employee = new Employee();
        //populate employee model

        postrequest.Method = Method.POST;
        postrequest.Resource = "api/Employee/CreateEmployee";
        postrequest.AddHeader("Accept", "application/json");
        postrequest.AddHeader("Content-Type", "application/json");
        postrequest.RequestFormat = DataFormat.Json;

        postrequest.AddBody(new { emp = employee, listId = 2 });
        var res = client.Execute(postrequest);

The error that I get is that employeeType parameter comes in as null. Am I formatting this properly? Is this something that's even possible to do?

When i remove the employeeType parameter from the WebApi action method and modify the request to:

        postrequest.AddBody(employee);

everything works fine.

any ideas? Thanks

1 Answer 1

1

if you are expecting employeetype from uri and if its not part of defined route, you can send it as query string parameter...Ex:

api/Employee/CreateEmployee?employeeType=

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I'll give this a try. But is it possible to pass it in the body rather than as part of the JSON string rather than have it in the URL?
you cannot have multiple parameters reading from body. only one is allowed.
Thank you Kiran. For those looking for more info, here's a pretty good article on parameter binding: blogs.msdn.com/b/jmstall/archive/2012/04/16/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.