简体   繁体   English

宁静的MVC API操作需要POST上的URL参数

[英]Restful MVC API action requires URL parameters on POST

In a controller, I have a method like this: 在控制器中,我有一个像这样的方法:

public class FooController : ApiController
{
    [HttpPost]
    public HttpResponseMessage ApplySomething(int id)
    {
        ...
    }
}

When I do a POST request like .../Foo/ApplySomething/ and passing id=1 as POST values, I get the error: 当我执行诸如.../Foo/ApplySomething/类的POST请求并传递id=1作为POST值时,出现错误:

{
    Message: "No HTTP resource was found that matches the request URI '.../Foo/ApplySomething/'."
    MessageDetail: "No action was found on the controller 'Foo' that matches the name 'ApplySomething'."
}

But when I change the URL to have the ID (like .../Foo/ApplySomething/1 ) it works, but getting the value from the URL, not from POST values. 但是,当我更改URL以使其具有ID(例如.../Foo/ApplySomething/1 )时,它可以工作,但是从URL中获取值,而不是从POST值中获取。

What I'm doing wrong? 我做错了什么?

By default, Web API uses the following rules to bind parameters: 默认情况下,Web API使用以下规则来绑定参数:

  • If the parameter is a “simple” type, Web API tries to get the value from the URI. 如果参数是“简单”类型,则Web API会尝试从URI中获取值。 Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. 简单类型包括.NET基本类型(int,bool,double等),以及TimeSpan,DateTime,Guid,十进制和字符串,以及带有可从字符串转换的类型转换器的任何类型。 (More about type converters later.) (稍后会更多有关类型转换器的信息。)
  • For complex types, Web API tries to read the value from the message body, using a media-type formatter . 对于复杂类型,Web API尝试使用media-type formatter从消息正文读取值。

Given those rules, if you want to bind the parameter from the POST body simply add a [FromBody] attribute in front of the type: 给定这些规则,如果要绑定POST正文中的参数,只需在类型前面添加[FromBody]属性:

public HttpResponseMessage ApplySomething([FromBody] int id) { ... }

For more information please see the documentation . 有关更多信息, 请参见文档

Try this : 尝试这个 :

public class FooController : ApiController
{
    [HttpGet]
    public HttpResponseMessage ApplySomething(int? id=0)
    {
        ...
       return View();    
    }
    [HttpPost]
    public HttpResponseMessage ApplySomething(FormCollection Form,int? id=0)
    {
        ...
       return View();    
    }
}

Now Try this url .../Foo/ApplySomething?id=1 现在尝试使用此网址.../Foo/ApplySomething?id=1

Hopefully it works...! 希望它能工作...!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM