简体   繁体   中英

Why is WebAPI action found as GET but 404 when I use POST?

I have an action on my controller called GetPhotos. When I call the action as a GET with the appropriate parms, the action is called and everything works great. (I'm using attribute routing)

GET Code

    [Route("getphotos")]
    public IHttpActionResult GetPhotos(string userid, string password, string system, string outstation, string systemno, string version, string compid, string photono)
    {
        //Do some logic here
        return OK();
    }

GET call

GET http://localhost:60672/getphotos?userid=User1++&password=12345&system=UserSystem&outstation=9&systemno=3&version=6.78&compid=mycomputername&photono=003573
HTTP/1.1
User-Agent: Fiddler
Host: localhost:60672
Content-Type: application/x-www-form-urlencoded
Content-Length: 0

However, when I change the action to HttpPost and change my call to a POST call (via Fiddler), I get back a 404.

POST Code

    [HttpPost]
    [Route("getphotos")]
    public IHttpActionResult GetPhotos(string userid, string password, string system, string outstation, string systemno, string version, string compid, string photono)
    {
        //Do some logic here
        return OK();
    }

POST Call

POST http://localhost:60672/getphotos HTTP/1.1
Content-Type: application/x-www-form-urlencoded
User-Agent: Fiddler
Host: localhost:60672
Content-Length: 170
Pragma: no-cache

USERID=User1&PASSWORD=12345&SYSTEM=UserSystem&OUTSTATION=9&SYSTEMNO=3&VERSION=6%2E79&COMPID=mycomputername&PHOTONO=003573

Why am I unable to find the action with a POST?

I found the answer here .

Apparently, I had two things wrong. I'm used to MVC and was trying to do things the MVC way rather than the WebAPI way.

First, I needed the [FromBody] attribute in front of my parameters since that is where I wanted the model binding to pull from.

However, it also appears that WebAPI will only allow one [FromBody] parameter for any given action. So, what I wound up doing was creating a Model that encapsulated all my values and changed my method definition to look like this:

public IHttpActionResult GetPhotos([FromBody] GetPhotoModel model) { ... }

Hope this saves you from some of the same frustration!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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