【问题标题】:Making a simple Web API post request发出简单的 Web API 发布请求
【发布时间】:2017-04-30 10:55:36
【问题描述】:

我真的很难在 url 中发出基本的帖子请求以支持 web api 教程。

我想在浏览器中做这样的事情:http://localhost:59445/api/group/post/?newvalue=test 并让帖子注册。但是我似乎无法正确地形成请求。这样做的正确方法是什么?

我收到的错误是:

{"Message":"请求无效。","MessageDetail":"参数字典包含方法'System.String Get的不可空类型'System.Int32'的参数'id'的空条目(Int32)' in 'twin_groupapi.Controllers.GroupController'。可选参数必须是引用类型、可空类型或声明为可选参数。"}

我的模特:

    public class Group  
    {
     public Int32 GroupID { get; set; }
     public Int32 SchoolID { get; set; }
     public string GroupName { get; set; }
    }

路由:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

控制器:

    //[Route("api/Group/Post")]
    [HttpPost]
    public void Post([FromUri] string NewValue)
    {

        string newstring = NewValue;

    }

【问题讨论】:

  • 你有另一种方法,名字post和动词为httpget
  • 只有其他动词是// GET: api/Group [Route("api/Group/Get")] [HttpGet] public Array Get()

标签: c# asp.net-web-api


【解决方案1】:

在浏览器中点击 URL 只会执行 GET 请求。

您可以:

  • 创建一个简单的<form> 并将其方法设置为POST 并形成输入以输入您要发送的值(如NewValue),或者
  • 编写一些 JavaScript 以使用您最喜欢的框架创建 AJAX POST 请求,或者
  • 使用Postman 之类的工具来设置、调用它并检查结果。

【讨论】:

    【解决方案2】:

    错误消息很可能来自您的 Get() 方法。

    正如@StriplingWarrior 所说,您正在发出GET 请求,而该方法被标记为[HttpPost]。如果您在浏览器中使用开发人员工具(大多数现代浏览器中的 F12 来激活它们),您可以看到这一点。

    看看How do I manually fire HTTP POST requests with Firefox or Chrome?

    注意:参数名称的 c# 约定是驼峰式,第一个字母是常见的,而不是大写,例如string newValue

    【讨论】:

      猜你喜欢
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2020-01-28
      相关资源
      最近更新 更多