c# - 如何在 C# 中定义和调用 api Post

标签 c# asp.net-web-api

我之前在 MVC 中创建过 POST/GET 请求。

在我的家庭 Controller 中

    [HttpPost]
    public string Index(int Value)
    {
        return Value.ToString();
    }

并使用表单数据设置 chrome 扩展 POSTMAN

我可以使用值为“1”的变量“Value”调用 http://localhost/mvcApp/ 并得到一个字符串“1”作为返回

但是当我创建一个 surveyController 时:ApiController 在我调用 http://localhost/mvcApp/api/survey/ 时不起作用

    public string Post(int Value)
    {
        return Value.ToString();
    }

"Message": "No HTTP resource was found that matches the request URI 'http://localhost/mvcApp/api/survey/'.",

"MessageDetail": "No action was found on the controller 'survey' that matches the request."

我不确定错误是出在创建 api 的方式上,还是出在 POSTMAN 尝试调用 api 的方式上。因为那个'.'

也可以在我的 HomeControler 索引中尝试

client.BaseAddress = new Uri("http://localhost/mvcApp");
var result = client.PostAsync("/api/survey", new
{
   Value = 1                    
}, new JsonMediaTypeFormatter()).Result;

if (result.IsSuccessStatusCode) // here return Not found

最佳答案

WebApi Controller 的约定与普通 MVC Controller 的约定不同。

基本上,问题是您不能像您那样指定 int 参数。

在你的 WebApi Controller 中试试这个:

// nested helper class
public class PostParams {
    public int Value { get; set; }
} 

public string Post(PostParams parameters) {
    return parameters.Value.ToString();
}

看看它是如何工作的。

这是一篇关于在 POST 请求中将参数传递给 WebAPI Controller 的详尽文章: Passing-multiple-POST-parameters-to-Web-API-Controller-Methods

长话短说,这些是约定,粗略地说:

  • 不能在参数中捕获 POST 表单名称-值对
  • 如果该类是您的方法参数之一的参数类型,您可以在类的属性中捕获它们
  • 可以在方法参数中捕获查询参数

编辑

如果您希望使用 C# 测试您的 WebAPI 服务器,您可以按照以下步骤操作:

  1. 创建一个漂亮的控制台应用程序(最好在同一个解决方案中)
  2. 添加Web API Client此控制台应用程序的 NuGet 包
  3. 让你的 Program.cs 做这样的事情。

以下代码使用 C# 5.0 async and await运营商。 它还使用 Task类和 anonymous types . 如果您对这些内容感兴趣,我已经指出了官方 MSDN 文章(单击链接)。

using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleApplication1 {
    class Program {

        public static void Main(string[] args) {
            Test().Wait();
        }

        private static async Task Test() {
            HttpClient client = new HttpClient();

            await client.PostAsJsonAsync(
                "http://localhost/mvcApp/api/survey/",
                new {
                    value = 10
                }
            );
        }

    }
}

关于c# - 如何在 C# 中定义和调用 api Post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29020271/

相关文章:

c# - StackExchange.Redis如何订阅多个 channel

c# - ASP.NET Web API 中的参数绑定(bind)

c# - ASP.NET WEB API 启动类

c# - 列出 DependencyObject 的属性?

c# - 在 C# 中,使用 tick 比较两个日期和按原样比较两个日期有什么区别

c# - mvc 中的强类型 web api 路由端点

asp.net-web-api - 是否可以在同一个应用程序中同时使用 NancyFx 模块和 WebAPI Controller ?

c# - 禁止 ASP.NET Web API 上具有空值的属性

c# - 将 CultureInfo 对象序列化为另一个类的属性

c# - Windows 身份验证 - Guid 应包含 32 位数字和 4 个破折号 (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)