asp.net-mvc - 使用 RestSharp 将多个参数发布到 webapi

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

我刚开始使用 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);

一切正常。

有什么想法吗?谢谢

最佳答案

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

api/Employee/CreateEmployee?employeeType=

关于asp.net-mvc - 使用 RestSharp 将多个参数发布到 webapi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12188430/

相关文章:

c# - 如何修复我的 Web API 2 Controller 以使用异步任务实现可伸缩性

asp.net - Session_Start 在默认 ASP.NET MVC3 项目上多次触发

asp.net-mvc - 错误: Make sure that the controller has a parameterless public constructor webapi

c# - 如何在asp.net MVC 2应用程序中的自定义ValidationAttribute内部访问其他属性值?

java - 从 Java 发送的 HTTP Post

c# - 如何将条件必需属性放入类属性中以使用 WEB API?

asp.net-web-api - WebApi 2 从 Google 身份验证 OpenID 更改 -> oAuth2 - 更改安全句柄

asp.net-mvc - ModelState.IsValid 是假的 - 但哪一个 - 简单的方法

php - 如何从中获取 Cookie curl?

http - 如果 ".com"之后有一个点,它是一个有效的 URL 吗?