routing,asp.net-web-api2,asp.net-web-api-routing , WebApi Routing not working for Post


WebApi Routing not working for Post

Question:

Tag: routing,asp.net-web-api2,asp.net-web-api-routing

My WebApiConfig has following routes

      // Web API routes
        config.MapHttpAttributeRoutes();

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

The Post WebApi method has got following Signatures

    [HttpPost]
    public IHttpActionResult Post(Employee emp)
    {
         .....

    }

When i try to call this method i am getting "Method not allowed"

If i change my Post method to following it starts working

    [Route("api/employee/post")]
    [HttpPost]
    public IHttpActionResult Post(Employee emp)
    {
        ...
    }

I am not getting what's the issue. I want this to work with attributes routing. Can anyone suggest what's the issue here. Does GET and Post routes gets confused ?


Answer:

Set your default route like below:

config.MapHttpAttributeRoutes(); //this enables attribute routing

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
); //this route is for conventional routing

now you can call your below API like http://{siteurl}/api/employee/ by conventional routing.

[HttpPost]
public IHttpActionResult Post(Employee emp)
{
   ...
}

now you can call your below API like http://{siteurl}/api/employee/post/ by attribute routing:

[Route("api/employee/post")]
[HttpPost]
public IHttpActionResult Post(Employee emp)
{
   ...
}

Here [Route] parameter adds route, which is called as attribute routing. You can find reference here Routing and Action Selection


Related:


No type was found that matches the controller name


asp.net,asp.net-web-api2
I've got the infamous Web Api No type was found that matches the controller name. I had this web service working until we did a little restructuring of the file system and classes and now I'm getting this error. The File system sits as default with the Controllers and Models...

Web Api and where should I contorol Request Header data


asp.net-web-api,asp.net-web-api2
In Asp.net Web Api, I want to control, request "access token" key is (which is in request header) valid or not. But I cound't decide where should I implement this kind of control. ActionFilter or controller constructor etc. etc.

Web API Returning a 405. Shouldn't it be a 404?


rest,asp.net-web-api,asp.net-web-api2,asp.net-web-api-routing
I've got a VendorsController that supports GET (by id) and POST (with a model). They are working as expected when called through the intended routes. However, I noticed that if I add an id to the POST route (ie add "/5" to "api/vendors"), I get a 405, with Response Body...

Angular $routeProvider and Controller As Syntax


angularjs,routing,angularjs-scope,angularjs-routing,ngroute
Can anyone tell me if it is valid to use $routeProvider with Controller as syntax? I am having issues accessing <h1>{{kickController.foo}}</h1> from the controller where this.foo resides. angular.module('ucp.kick', ['ngRoute']).config(function($routeProvider, APP_BASE_URL) { return $routeProvider.when(APP_BASE_URL + 'kicks', { reloadOnSearch: false, navitem: true, name: 'Kicks', templateUrl: 'kick/partials/kick.html', controller: 'kick as KickController' }); });...

File upload web api 2.0 error after deployment on IIS 8.5


c#,iis,file-upload,asp.net-web-api2
The below code works very well on development environment VS 2012, the images are saved to App_Data. When I deployed the same on Win 8.1, IIS 8.5, the App_Data was missing. I manually create the folder and set the properties as given in http://hintdesk.com/tutorial-publish-asp-net-web-api-in-iis-8-5-and-windows-8-1/. I am seeing strange behavior as...

Autofac - DelegatingHandler (HttpMessageHandler) Registration


c#,web-api,asp.net-web-api2,autofac,ioc-container
I have a custom DelegatingHandler in a class library that I need to register with Autofac. The webapi host resolves it's dependencies on runtime, so the host has no references to this library. public class LocalizationHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken ) {}...

Route parameter with slash “/” in URL


asp.net-web-api,routing,asp.net-web-api2,asp.net-web-api-routing,attributerouting
I know you can apply a wildcard in the route attribute to allow / such as date input for example: [Route("orders/{*orderdate}")] The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI: [Route("orders/{orderdate}/customers")] ? EDIT:...

how to update multiple data in entityframework through async web api


entity-framework,asp.net-web-api,async-await,web-api,asp.net-web-api2
I am using web api 2, and entity framework 6. I have created an async web api, which updates all the records at once. I am also using Autofac for dependency injection. My service interface is as follows : Task<Approval> TakeAction(int id, bool isApprove) void TakeAction(bool isApprove) These are my...

Why does this MVC action return a 404 response in IE11


ajax,asp.net-mvc,routing
I have written an mvc action that works in Chrome and Firefox but not in IE11. Using IE11 it returns a 404 response code. Controller: [HttpDelete] public ActionResult DeleteAction(int ActionID) { return Json(_Logic.DeleteAction(ActionID), JsonRequestBehavior.DenyGet); } Calling JS: Ajax_Proxy.DeleteAction = function (_actionID, successCallback, failureCallback) { return $.ajax({ type: "DELETE", datatype: 'json',...

Leverage MultipleApiVersions in Swagger with attribute versioning


attributes,asp.net-web-api2,swagger,swagger-ui,swashbuckle
Is it possible to leverage MultipleApiVersions in Swagger UI / Swashbuckle when using attribute routing? Specifically, I implemented versioning by: using System.Web.Http; namespace RESTServices.Controllers.v1 { [Route("api/v1/Test")] public class TestV1Controller : ApiController { ... } Version 2 would be in a v2 namespace. In a controller named TestV2Controller. The route would...

No action was found on the controller that matches the request


c#,asp.net,ajax,asp.net-mvc,routing
Sorry for the lame question. I've already read all similar questions and still can't resolve my issue. I'm getting 'No action was found on the controller that matches the request' error when calling from ajax: $.ajax({ url: '/api/ToyEdit/Post/', dataType: "json", type: "POST", contentType: 'application/json; charset=utf-8', data: JSON.stringify({toyId: 1, toy: 'asd'}),...

Node forward path request to another server


node.js,express,routing,routes,request
Currently have a website running a node server that handles all requests for example.com and I created a completely separate wordpress blog on a separate server (running apache) that I would like served on a path like example.com/blog at 172.23.23.23 IP address. The wordpress server doesn't share any code or...

WebApi Routing not working for Post


routing,asp.net-web-api2,asp.net-web-api-routing
My WebApiConfig has following routes // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { controller = "Employee", action = "Get", id = RouteParameter.Optional } ); The Post WebApi method has got following Signatures [HttpPost] public IHttpActionResult Post(Employee emp) { ..... } When i try to call...

WebApi Serving Videos on Mobile Devices


ios,html5-video,mobile-safari,asp.net-web-api2
I'm using WebApi to serve videos on a website. I've tested this on all major desktop browsers and the HTML5 Video tag plays the video as expected. However, I can't get this to work on iPhones (Mobile Safari). The Get() method is never called even after pressing the play button....

Multiple routes with multiple domains


symfony2,routing
Let's say I've got a website with multiple (sub)domains: acme.com (USA) acme.nl (Netherlands) be.acme.eu (Belgium) de.acme.eu (Germany) fr.acme.eu (France) etc... I thought this should be very simple to configure, so I made this routing.yml: usa: host: "acme.com" resource: "@WebsiteBundle/Controller/" type: annotation defaults: country: "en" netherlands: host: "acme.nl" resource: "@WebsiteBundle/Controller/" type:...

Asp.net MVC Routelink null controller parameter


c#,asp.net,asp.net-mvc,asp.net-mvc-4,routing
I have two routes, the default one routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); I added another route, sometimes the parameter will by a string routes.MapRoute( name: "ByName", url: "{controller}/{action}/{name}", defaults: new { controller = "Home", action =...

Select Mongoose Model Based on Express Route


express,routing,mongoose
I think this might be a basic question, but looking for the best approach. I'm building an express app that should route to one of four different Mongoose models depending on the route. Something like this: app.get('/:trial', function(req, res){ var trial = req.params.trial; trial.find(function(err, records) { if (err) res.send(err); res.json(records);...

Where should I put Symfony third-party bundle's routing configuration?


php,symfony2,routing,symfony-routing
I have SonataAdminBundle, SonataUserBundle and LiipImagineBundle installed in my Symfony 2 application. According to their installation instruction, I put their routing configuration in /app/config/routing.yml. _liip_imagine: resource: "@LiipImagineBundle/Resources/config/routing.xml" admin: resource: "@SonataAdminBundle/Resources/config/routing/sonata_admin.xml" prefix: /admin _sonata_admin: resource: . type: sonata_admin prefix: /admin sonata_user: resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml' prefix: /admin...

Can I receive a JavaScript Object on an API WITHOUT a Corresponding C# Object?


javascript,c#,asp.net-web-api2
I have a Web API 2 controller. I am sending a JavaScript Object from the client in a call: myObject = {propertyOne: 'Hi', propertyTwo: 'Bye'} Do I HAVE to make a class with those properties in C# to receive the object as an argument to the Web API controller? public...

XSS in angularjs app and web api 2


angularjs,xss,asp.net-web-api2,antixsslibrary
I have a web application. I am using Angularjs and Web Api2. I have a simple form where user can insert some free text that will be send via email to other people. The text is also saved on db and later can be shown in a web site page....

Zend Framework 2 routing error: resolves to invalid controller class or alias


zend-framework,routing,zend-framework2,zend-framework-mvc,zend-framework-routing
I'm trying to learn Zend Framework 2 and I have their skeleton application up and running. In order to access it I visit http://localhost:8080/. When visiting that link it displays their generic Zend page. What I want to be able to do is visit http://localhost:8080/application/test and have it bring me...

Restrict laravel to open url that is not in route


php,laravel,routing,laravel-5,laravel-5.1
I am Learning laravel now. Today I came across a problem that surprised me. I open this link in my browser: http://localhost/laravel/project/ch/resources/views/pages/blog.blade.php And I expect error 404. but it opens contains of this file. So, How to restrict laravel to do this. I want laravel to open only url mentioned...

web api FromUri and FromBody attributes misunderstanding


asp.net-web-api,web-api,asp.net-web-api2
I found this example in google: public string GetValue([FromUri]Book b, [FromUri]Author a) { return b.Name + " ("+a.AuthorName+")"; } public string PostValue([FromBody]Person p) { return p.FirstName; } I can't understand what is the point of [FromUri] attribute if HTTP GET method send data only as part of the URl respectively,...

Is it possible in laravel 5 to show a pretty url to the user, and a practical url to the app?


routing,routes,laravel-5,friendly-url,slug
I have this url: mywebsite.com/user/1/edit I want my users to see this: mywebsite.com/edit-your-profile/ Is this possible when using Route::resource('user', 'UserController');? If yes, how do I do it :) ? I still want my app to be able to see user/1/edit as I use it in my middleware to prevent unauthorized...

How to access UrlHelper.Action or similar from within Global asax


c#,routing,asp.net-mvc-5
I am trying to prepare a 301 redirect for a typo I made 'recieved' I am struggling to find a way of getting the url from the action and controller names. I am aware of UrlHelper.Action but it does not exist within Global.asax. How do I gain access to this...

Web API 2 requires trailing slash for custom attribute routing to work


asp.net-mvc,rest,asp.net-web-api2
I have created a Web API 2 project and although the APIs work fine, I must enter a trailing slash for them to do so. This results in a 404 http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699 This shows the JSON response as intended http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699/ I have another controller with a custom action that works fine....

Ruby-on-Rails Voting Partial Routing


ruby-on-rails,routing,voting
I have a voting feature on my app but can't route back to the same page with the vote applied. I know I have to fill in the link_to methods but my understanding of routing/ruby syntax is a bit limited, so I'm not even sure [post, vote] is correct. I...

SAPUI5/OPENUI5 - Routing with Dialogs


routing,dialog,sapui5,openui5
I´m currently stuck with the combination of routing and dialogs. I have a view with list elements and when I click on an element in the list I want the Detail view to be shown in a Dialog (Popup). The thing is, I also want the ID of the list...

How to deal with extra “/” in phpleague route?


php,web-services,routing
I am setting endpoints for my web application like this: $router = new League\Route\RouteCollection; function user_action (Request $request, Response $response) { // some logic . . . return $response; } $router->addRoute('GET', '/user', 'user_action'); /user endpoint works well. However when I use /user/ (extra slash in the end) I get a...

Subdomain routing not working on Laravel 5 - WAMPServer


apache,.htaccess,laravel,routing,wamp
I am trying to implement static and dynamic subdomain routing in my application. It is not working as expected. I am using WAMPServer in my local machine. routes.php Route::get('/', '[email protected]'); Route::group(['domain' => 'api.letsplay.dev'], function () { Route::group(['prefix' => 'v1'], function () { Route::get('users', function () { return "Success"; }); });...

Routing in Sinatra


ruby,web,routing,sinatra
I have an application where the user fills out a form at /search and I want that to output to /search/results. In my app.rb, I've attempted to call post '/search' do ... erb :search/results end However that fails. My directory structure is: views -search --results But it fails. Where am...

Change resources path


ruby-on-rails,ruby,routing
I'm using Rails 4 I have a routes.rb file that looks like: resources :books However, I'd like the urls in the application to end up looking like /b/101 instead of /books/101. I realize I could go through and rename each resource path individually, but is there not a way to...

web api Bad Request when getting access token after moving to production


c#,asp.net,asp.net-web-api2
I have a web api that is working great in test using an access token / bearer authentication. I authenticate and make requests using HttpClient. Easy. Here is the basic web client setup. The base address is a constant that I change when moving to production. public static HttpClient GetClient()...

Re-transmission concept in TCP


tcp,routing,tcp-ip,osi
Server sent data to client, but client didn't send ACK for the data . So once RTT completed , Server will resend data to client again .... like that how long it will try to send the data ? What is the maximum time server will try to send the...

Simple.OData.Client - Unable to invoke Action that accepts entity collection parameter


odata,asp.net-web-api2,simple.odata
I get error "The parameter 'wheels' is of Edm type kind 'Collection'. You cannot call CreateCollectionWriter on a parameter that is not of Edm type kind 'Collection'." Below are details of my setup: Web API 2.2 OData v4 service : I have defined Action in WheelsController class in my...

Symfony/Twig how to render a Route set by anotation?


php,symfony2,routing,twig,url-routing
Let's say I have this code in a controller: <?php namespace Foo\BarBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc; /** * @Mvc\Route("/foo/bar") */ class TestController extends Controller /** * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"}) * @Mvc\Template * * @return view */ public function testAction($id) { return array('test' => $id); } } How...

Open page url in modal on a page (Facebook Photo URLs)


javascript,jquery,angularjs,routing,angularjs-routing
P.S. I am using html5Mode to remove '#' in routing in below scenario Removing the hashtag from AngularJS urls (# symbol) Consider I have two main pages.One is photos where thumbnails are provided and whose url is /someSlug/photos. Other is the url of a single photo '/someSlug/photos/somePhotoId' which shows a...

Codeigniter Select JSON, Insert JSON


json,codeigniter,select,insert,routing
I have very simple users database: user_id, user_name, user_email My model this: class Users extends CI_Model { private $table; private $table_fields; private $table_fields_join; function __construct() { parent::__construct(); $this->table = 'users'; $this->table_fields = array( $this->table.'.user_id', $this->table.'.user_name', $this->table.'.user_email' ); $this->table_fields_join = array(); } function select(){ $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));...

$StateProvider Remove Child View Nesting


angularjs,routing,angular-ui-router,angularjs-ui-router
I am new to angular ui routing . I am creating a sample application and want to display parent and child view separately . I mean when parent item gets selected child view will be displayed and parent view would be hidden . If I add ui-view to parent view...

OData Annotations do not appear when not localhost


odata,asp.net-web-api2
I'm building an OData response by throwing a standard HttpResponseException. The exception itself is built with an HttpResponseMessage based on ODataError. new ODataError() { ErrorCode = code, Message = message, InnerError = new ODataInnerError() { Message = innerException.Message, StackTrace = innerException.StackTrace, TypeName = innerException.GetType().Name }, InstanceAnnotations = annotations }); The...

Rails routing link to specific show


ruby-on-rails-4,routing
This question seems a little basic, but considering I have 'pages#show' with a show page with url 'history'. How could I add this specific show page to a link: = link_to 'History', pages_path(@?????) PD1: I would prefer avoid using :id since I tend to seed a lot of data, and...

I don't understand routing


php,routing,flightphp
I am trying to learn a PHP framework. But I'm having some difficulties understanding some of the concepts of routing. I've chosen to use Flight. Their homepage shows: require 'flight/Flight.php'; Flight::route('/', function(){ echo 'hello world!'; }); Flight::start(); And I don't understand what they're using Flight::route... for. What am I missing?...

How to add menus/ subtopics for meteor site?


javascript,node.js,meteor,routing,meteor-blaze
I am new to meteor. I followed the tutorials and successfully making simple interfaces like below. I tried finding examples to add menus/ subtopics like this which does not reload the page when clicked, but I couldn't find any examples. Could you please give me an example how to do...

Implementing find node on torrent kademlia routing table


table,routing,bittorrent,dht,kademlia
I, already, reviewed a number of documents on this topic but there is something not exactly clear. For example bit torrent document (http://www.bittorrent.org/beps/bep_0005.html) states The routing table is subdivided into "buckets" that each cover a portion of the space. An empty table has one bucket with an ID space range...

Unit testing ASP.NET Web API 2 Controller which returns custom result


c#,.net,unit-testing,asp.net-web-api,asp.net-web-api2
I have a Web API 2 controller which has an action method like this: public async Task<IHttpActionResult> Foo(int id) { var foo = await _repository.GetFooAsync(id); return foo == null ? (IHttpActionResult)NotFound() : new CssResult(foo.Css); } Where CssResult is defined as: public class CssResult : IHttpActionResult { private readonly string _content;...

Using A Service DB Context as WebApi OData Context


c#,wcf,odata,asp.net-web-api2
I'm trying create a OData service using Webapi 2. I've already created a working example that works with a local context. Now, I want to use a Context Provided from a seperate WCF Service. WebApiConfig.cs: public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id...

Angular not responding to any routes with ui-router - URL just disappears when I enter


angularjs,node.js,express,routing,angular-ui-router
I'm using NodeJS+Express to serve an HTML page with an Angular app. It seems to work fine when it loads. There are no errors. Problem is that that page is pretty much blank - except for the header. But the part that is supposed to go where <div ui-view></div> is,...

Entity Framework throws Invalid object name


c#,sql-server,entity-framework,ado.net,asp.net-web-api2
I have a DB in SQL Server with several tables. I have created a Class Library project in VS2013. Created a DBContext, added the database as a ADO.NET file and created a repository for running the queries. I have created a Web API2 empty project with a controller for creating...