Solved

WebAPI POST Route Config?

Posted on 2014-04-05
10
2,084 Views
Last Modified: 2014-04-07
Using VS2012 and WebApi 4

I'm trying to POST a new book title and cannot get the routing correct.

My querystring: http://localhost:51377/api/books/post?name=natgeo

Web page error:

<Error><Message>No HTTP resource was found that matches the request URI 'http://localhost:51377/api/books/post?name=natgeo'.</Message><MessageDetail>No route providing a controller name was found to match request URI 'http://localhost:51377/api/books/post?name=natgeo'</MessageDetail></Error>


[WebApiConfig]
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "post",
                routeTemplate: "api/{Books}/{post}/{name}",
                defaults: new { name = "" }
            );
        }
     }

[Controller]
 public class BooksController : ApiController
 {
        public HttpResponseMessage Post(string name)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (SampleDbEntities entities = new SampleDbEntities())
                    {
                        Book book = new Book
                        {
                            BookName = name
                        };

                        entities.Books.AddObject(book);
                        entities.SaveChanges();
                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, "Model state is invalid");
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
}
0
Comment
Question by:WorknHardr
  • 4
  • 3
  • 3
10 Comments
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
Comment Utility
Change your route config to:

routeTemplate: "api/{controller}/{action}/{name}",

Open in new window

0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
My querystring: http://localhost:51377/api/books/post?name=natgeo
POST data is not passed in a query string but in another 'container' that is not visible.  The example page you linked to on your other question does show how to do it but it is not as simple as a GET with a query string.
0
 

Author Comment

by:WorknHardr
Comment Utility
I know JSON is used to POST. I'm trying to learn how to POST or PUT with a URL string.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
@Dave Baldwin

POST data is not passed in a query string but in another 'container' that is not visible.
Technically speaking, there is nothing in the RFC that forbids data from being passed in the querystring of a POST operation. It is generally discouraged, though.

@WorknHardr

My previous comment was off the cuff, so does the fact that you haven't responded to it imply that it did not work?
0
 

Author Comment

by:WorknHardr
Comment Utility
Sorry Kaufmed, I'm out of the office and haven't applied your code yet!
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:WorknHardr
Comment Utility
I'm new to the Web API and trying to learn its capabilities, limitations, pro's, con's, etc...
I'm still curious why it's much easier to GET and so difficult to POST or PUT using a simple query string. It's a SOAP issue I suppose and security concerning illegal WRITES. After becoming more educated about a Web API, I will use AngularJS and JSON to consume a .Net Web API service.
I understand Web API 2 does even more.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
I'm still curious why it's much easier to GET and so difficult to POST or PUT using a simple query string.
Well, as I mentioned above, you can (sometimes) use a querystring with a POST or PUT, but this isn't how most systems operate, so you would be doing something that is non-standard. If you continue down that path, then you would want to ensure that you have appropriate documentation of your non-standard implementation.

Also, you can only do simple key/value with queystring. Complex data should be passed in a request body...which is exactly what is expected when using POST and PUT.

It's a SOAP issue...
Whoa! SOAP and REST are two different things. It is possible to send/recieve SOAP (to an extent, as I understand) via a RESTful service, but I don't think anyone does this. So my question to you would be:  Do you have a SOAP service or a REST service?
0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 250 total points
Comment Utility
Sorry but you are misunderstanding the definitions of GET and POST.  Only GET methods use the querystring, POST does not and has not ever used that.  You can use Both methods in a single request but the receiving page has to check both methods when you do that.  On the receiving page, 'request.querystring()' is used to load the GET information and 'request.form()' is used to load the POST information.

All these things are well defined.  http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html is the 'official' but somewhat obscure definition.  http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol is a somewhat more concise description.
0
 

Author Closing Comment

by:WorknHardr
Comment Utility
Yup, this works for routing:    
        routeTemplate: "api/{controller}/{action}/{name}",

And here is the page return:
         <Error><Message>The requested resource does not support http method 'GET'.</Message></Error>

I'm learning, thx...
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
You're welcome, glad to help.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
For some reason Google Apps has decided to reserve 'www' for your new domain which results in an error when trying to map the web address 'www' to a certain site in your Google Sites. The error is 'this address is already being used' and after some …
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now