asp.net-web-api,routing,asp.net-web-api2,asp.net-web-api-routing,attributerouting , Route parameter with slash “/” in URL


Route parameter with slash “/” in URL

Question:

Tag: 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:

I know there are few options to solve the issue by refactoring the code so please do not offer a solution something like:

  1. change the route template to [Route("orders/customers/{orderdate}")]
  2. change the date to a different format (e.g. "dd-mm-yyyy")

Answer:

@bet.. I think the genericUriParserOptions is no longer applicable to .net 4.5 or later..

also as suggested by @JotaBe, you might need to correctly decode the url request. In most case the %2F will be automatically translated to a slash '/' so if you need to escape it you will need to decode the '%' char in the first place.. so your URL: will look something like: www.domain.com/api/orders/23%252F06%252F2015/customers

Notice the characters '%252F' will be translated to the actual '%2F'

EDIT

Ok here is the complete solution (Tried it and working for me):

  1. Assuming you have an API endpoint like so:

    [Route("orders/{date}/customers")]
    public HttpResponseMessage Get(string date)
    {
    }
    
  2. In the web.config you will need to set the requestPathInvalidCharacters to empty which tells the asp.net to allow all request

    <system.web>
        <httpRuntime targetFramework="4.5" requestPathInvalidCharacters=""/>                
    </system.web>
    <system.webServer>
        <security>
          <requestFiltering allowDoubleEscaping="true" />
        </security>
    </system.webServer>
    
  3. When the client sending the request to the API you will need to make sure to escape the '%' like so:

    www.domain.com/api/orders/23%252F06%252F2015/customers

  4. You then need to decode the request

    [Route("orders/{date}/customers")]
    public HttpResponseMessage Get(string date)
    {
            DateTime actualDate = DateTime.Parse(System.Net.WebUtility.UrlDecode(date)); // date is 23/06/2015
    }
    

Related:


Web API Basic Auth inside an MVC app with Identity Auth


c#,authentication,asp.net-web-api,asp.net-mvc-5
So I have a C# MVC app using Identity for its authentication. I now have a need to expose a few things via Web API to some of my clients. Instead of building a separate app, project, deployment... I've simply added an API Controller to my existing project. To keep...

$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...

Can't access any of Linq methods


linq,asp.net-web-api
I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

Web API translating input into random int


c#,post,asp.net-web-api,json.net
not sure whether the subject is the best description for this problem but I am getting an unusual problem where I have a single Web API operation and a single field on a request and for some odd reason the value gets manipulated. Depending on the input this gets converted...

Paging in .NET Web API


c#,.net,asp.net-web-api,odata,paging
I have to do paging for an odata endpoint built using Entity Framework . I know I can do it using private ODataQuerySettings settings = new ODataQuerySettings(); settings.PageSize = myPageSize; // I keep this value in web.config of solution and options.ApplyTo(IQueryable, settings); But I am constrained not to use ApplyTo...

how to post objects from angular to a webapi controller


javascript,c#,angularjs,asp.net-web-api,http-post
I am creating a pdf using pdfsharp. I need to pass the chart legend data(name,color) to the pdfsharp controller. I am using a angular $http post, a ajax post would be fine as well. the error I am getting is Request...

Web API and MVC in the same project with Session States


c#,asp.net-mvc,asp.net-web-api,session-state
I'm been working around an ASP .Net MVC application that is going take log in requests from different sites with different configurations (so I cannot use the FormsAuthentication SSO way). The way I decided to resolve this was by creating temporal login request tokens, so each token could be used...

Manually validate Model in Web api controller


asp.net,asp.net-mvc,asp.net-web-api
I have a class called 'User' and a property 'Name' public class User { [Required] public string Name { get; set; } } And api controller method is public IHttpActionResult PostUser() { User u = new User(); u.Name = null; if (!ModelState.IsValid) return BadRequest(ModelState); return Ok(u); } How do i...

No 'Access-Control-Allow-Origin' header on one site, but not on another


c#,jquery,ajax,asp.net-web-api,cors
We have a system made up of a website, written in ASP.NET/MVC, and a webservices site, written in ASP.NET/WEBAPI. The user loads pages from the website, which make AJAX calls into the webservices site, using JQuery. We're building this with VS2013, and deploying it with MS's Web Deploy, run from...

struct table inside struct - ASP.NET - allegro webAPI


c#,asp.net,asp.net-web-api,struct
I stopped in one point. I'm writing a small ASP.NET application with WebAPI from polish site allegro.pl (it's similiar to ebay.com) This API have a method which returns me some data: (...) 3. searchArray | SearchResponseType[] Struct table, where are the information about offers that matches the question (...) Inside...

Access the web project's folder from the WebAPI project


c#,asp.net-mvc,asp.net-web-api
My Asp.Net MVC project's folder structure is as shown above.Could you tell me how to access the web project's event-images folder from the webapi project ? I have implemented where I can access the webapi's event-images folder as shown below. Now I need to access web project's event-imagesfolder.How can...

Asp.net Web API Routing by action name fix


asp.net-mvc,rest,asp.net-web-api,asp.net-routing
I found this article at asp.net Learn website. I use this article to help me to create an API method to search in the database by email and not id. However, if you take a look at the article, you will be able to help me fix my problem as...

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...

Web Api 2 or Generic Handler to serve images?


c#,asp.net,asp.net-web-api
I want to create an image handler, but i am torn between using Web API 2 or just a normal Generic Handler (ashx) I have implemented both in the past, but which one is the most correct one. I found an old SO post LINK but is it still really...

Cannot read property 'client' of undefined using SignalR


asp.net-web-api,signalr,signalr-hub
I've been working all day on this with no luck. I have also tried (almost) every single SO question, but I didn't get it to work... I'm running web api with very simple SignalR push message and separately simple front end to show this push message. In my case the...

DataTables Warning: Requested unknown parameter 'pCodigo' for row 0


asp.net-web-api,datatables
I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error. Hope someone sees the problem. The html markup: <input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar"...

Exclude underlying objects when storing data using EF6


asp.net,entity-framework,asp.net-web-api
I have a class Ticket which has some properties. Three of these (View, Task and Key) properties are navigation properties. Those properties already exist in database even before a ticket has been stored. In my application I load those properties from the database first and then create a Ticket object....

WebApi Put how to tell not specified properties from specified properties set to null?


c#,.net,json,asp.net-web-api
Here is the scenario. There is an web api put call to change an object in sql server database. We want only to change the fields on the database object if they were explicitly specified on webapi call json. For example: { "Name":"newName", "Colour":null } That should change the Name...

OnAuthorization Method of AuthorizationFilterAttribute will execute every time when request arrives?


c#,asp.net-web-api
I am writing Web API ( v2.2 ) for accessing another REST API. Reason is that I want restrict some functional and provide more friendly data. In short I am writing wrapper for some REST API. I am providing authentication/authorization via my Implementation of AuthorizationFilterAttribute. Here is snippet of code:...

Null parameter on web api post method


c#,asp.net,asp.net-web-api
I have a very simple web api controller: public class CarrinhoController : ApiController { [HttpPost] public string Adiciona([FromBody] string conteudo) { return "<status>sucesso</status"; } } Now I'm running the server and trying to test this method via curl like this: curl --data "teste" http://localhost:52603/api/carrinho The request is arriving in my...

How to setup Request.Header in FakeHttpContext for Unit Testing


c#,unit-testing,asp.net-web-api,httpcontext
I have a FakeHttpContext I have been trying to modify to include some headers for testing purposes public static HttpContext FakeHttpContext() { var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id",...

How can I handle exceptions in Web API 1.0 at my BaseAPIController


.net,asp.net-web-api
I am currently using Web API 1.0 and .NET 4.0 I need a function that can take care of the noise of catching and handling exceptions in my Base API so that I dont need to write that in every RESTful operation. public int Get(WelcomeTeamNotes note) { try { return...

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...

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.

Enforce ordering of OData items even when $top is used


linq,entity-framework,asp.net-web-api,odata,iqueryable
I have a DbSet<Items> collection. The primary key is a Guid. I don't want to order by this primary key. I want to order by an editable decimal property named "Order". The code I have is very simple, and it works great until the user puts a "$top" parameter into...

Losing HttpContext with async await in ASP.NET Identity GetRolesAsync


c#,asp.net-web-api,async-await,asp.net-identity
This is more of an async/await question than ASP.NET Identity. I am using Asp.Net Identity, and have a custom UserStore, with a customized GetRolesAsync method. The UserManager is called from a WebApi controller. public class MyWebApiController { private MyUserManager manager = new MyUserManager(new MyUserStore()); [HttpGet] public async Task<bool> MyWebApiMethod(int x)...

Database error in web api


c#,sql,linq,asp.net-web-api,odata
I am trying to create an odata endpoint for a table valued function in sql database. I get the exception: The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. I am sure with my code and unable to...

What's the best way to map objects into ember model from REST Web API?


json,rest,ember.js,asp.net-web-api,ember-data
The topic of this post is: my solution is too slow for a large query return. I have a Web Api serving REST results like below from a call to localhost:9090/api/invetories?id=1: [ { "inventory_id": "1", "film_id": "1", "store_id": "1", "last_update": "2/15/2006 5:09:17 AM" }, { "inventory_id": "2", "film_id": "1", "store_id":...

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...

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...

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...

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);...

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:...

Passing complex array from Controller to View ASP.NET MVC


c#,asp.net,asp.net-mvc,asp.net-web-api
I have a model in my ASP.NET MVC application: public class SearchArrayModel { public long ID { get; set; } public string Name { get; set; } public struct AttribStruct { public string AttribName { get; set; } public string[] AttribValues { get; set; } } public AttribStruct[] AttribStructTable {...

Where should I store WebAPI controllers inside ASP.NET-MVC 5 project?


asp.net-mvc,asp.net-web-api,odata
I have completed an ASP.NET-MVC5 application(website) where I have lot of MVC controllers: I would like to extent the functionality of my application by exposing WEB API with OData. For instance I would like to create another controller for Person model class, but this time it should be Web API...

.NET web API calls are getting intercepted by angular js UI Router, returning HTML instead of calling API


javascript,angularjs,asp.net-web-api
I have an angularjs app, that sits on top of an MVC5 app and an WEB API backend. I am using UI Router for the Angular js routing and for now, have removed ALL $urlRouterProvider.when and $urlRouterProvider.otherwise calls, but still when I try to do a $http:get... it is returning...

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...

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...

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...

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'}),...

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)));...

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...

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' }); });...

Web API AuthorizeAttribute does not return custom response


c#,asp.net-web-api,asp.net-mvc-5
How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

query multi-level entity with filter at the lowest level


c#,asp.net,asp.net-web-api,linq-to-entities
So I have 3 entity classes: public partial class Event { public Event() { Recurrences = new HashSet<Recurrence>(); } public int Id { get; set; } public ICollection<Recurrence> Recurrences { get; set; } } public partial class Recurrence { public Recurrence() { AspNetUsers = new HashSet<AspNetUser>(); } public int Id...

Is it nessesarry to send credentials on every single request to MVC Web Api?


authentication,asp.net-web-api,web-api
I am about to create my first restfull web service where i chose MVC WEB API to be the "provider". After reading about authentication i am a little confused. My requirements is that on call to any url of webservice i want client to be authenticated, except sign in url....

httpwebrequest GET retry when connection is lost


c#,asp.net-web-api
My application uses a httpwebrequest to GET certain information from my WebAPI. What I'm trying to do is retry the request if the connection is lost or if there is no connection at all. public static string httpsGET(string passedweburi, string BCO) { string content = ""; //GET method HttpWebRequest HttpRequest...

Web api with mvc 6 get element based on string


c#,asp.net-mvc,asp.net-web-api,asp.net-5,asp.net-mvc-6
I am creating a web api using mvc 6. now i am trying to get a element from my db. the key in this table is a string (email adress). i do not have acces to this database so i cant change the key of this table. Now when creating...

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...