【问题标题】:Posting with multiple parameters to webapi using RestSharp使用 RestSharp 将多个参数发布到 webapi
【发布时间】:2012-08-30 08:48:49
【问题描述】:

我刚开始使用 RestSharp 和 WebApi,但遇到了一些问题。

我不确定这是否是最佳实践,甚至可能,但我将通过代码进行演示(这不是我的确切代码,但它是完全相同的概念)

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

我创建了一个控制台应用程序来使用 RestSharp 进行测试。这是我所拥有的:

        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);

我得到的错误是employeeType 参数为null。我是否正确格式化?这是什至可以做到的事情吗?

当我从 WebApi 操作方法中删除 employeeType 参数并将请求修改为:

        postrequest.AddBody(employee);

一切正常。

有什么想法吗?谢谢

【问题讨论】:

    标签: asp.net-mvc http asp.net-web-api restsharp


    【解决方案1】:

    如果您期望来自 uri 的employeetype 并且它不是已定义路由的一部分,您可以将其作为查询字符串参数发送...例如:

    api/Employee/CreateEmployee?employeeType=

    【讨论】:

    • 谢谢,我试试看。但是是否可以在正文中传递它而不是作为 JSON 字符串的一部分而不是在 URL 中传递它?
    • 您不能从正文中读取多个参数。只允许一个。
    • 谢谢基兰。对于那些寻找更多信息的人,这里有一篇关于参数绑定的好文章:blogs.msdn.com/b/jmstall/archive/2012/04/16/…
    猜你喜欢
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2013-03-15
    • 1970-01-01
    相关资源
    最近更新 更多