,,,web-api, , How to use the same route with different parameter types?

How to use the same route with different parameter types?



I have an Api controller with two different actions that take different parameter types.

    // GET: users/
    public IHttpActionResult GetUser(string emailAddress)

    // GET: users/1D8F6B90-9BD9-4CDD-BABB-372242AD9960
    public IHttpActionResult GetUserByReference(Guid reference)

Problem is multiple actions are found matching when I make a request to either. Looking at other answers I thought I needed to setup routes in the WebApiConfig like so...

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

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

What do I need to do so that each action is called based on the parameter type I pass in?

I'm very new to Web.Api any additional explanation text would be appreciated.


You do like below method declaration with attribute routing enabled: //declare method with guid 1st

public IHttpActionResult GetUserByReference(Guid reference)

and declare other method like below

// GET: users/
public IHttpActionResult GetUser(string emailAddress)

Please let me know, is this work for you ?


How to setup Request.Header in FakeHttpContext for Unit Testing

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

Web Api 2 or Generic Handler to serve images?

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

Convert SQL to linq statement


LINQ: Searching inside child entities


Getting users from another AD Domain using PrincipalContext


Web API Basic Auth inside an MVC app with Identity Auth


How to use ajax to post json string to controller method?





Cannot read property 'client' of undefined using SignalR,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...

Is it nessesarry to send credentials on every single request to MVC 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....

Knockout js unable to bind data using observableArray


Database error in web api

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

DataTables Warning: Requested unknown parameter 'pCodigo' for row 0,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"...

Inherited Property of Model is always returning Null Value


.NET web API calls are getting intercepted by angular js UI Router, returning HTML instead of calling 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...

Null parameter on web api post method

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

Linq Conditional DefaultIfEmpty query filter


Convert string value to english word


Embedding a Silverlight App into a MVC


MVC route attribute no controller,,

Losing HttpContext with async await in ASP.NET Identity GetRolesAsync

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

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

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

How detailed should your repository be? Testing issues [closed]


How do I properly send __RequestVerificationToken with an ajax request in MVC5




Produce different serialized JSON for a given class in different scenarios


How to get routevalues from URL with htmlhelpers or JavaScript?


Manually validate Model in Web api controller,,
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...

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

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

query multi-level entity with filter at the lowest level

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

MVC/Razor: Error at Viewbag.Title




Web API translating input into random int

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

Best approach to upgrade MVC3 web app to MVC5?


MvcSiteMapProvider - Enhanced bootstrap dropdown menu


how to update multiple data in entityframework through async web api

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

Passing complex array from Controller to View ASP.NET MVC

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

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

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

Route parameter with slash “/” in URL,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:...

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

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


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

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

Web API AuthorizeAttribute does not return custom response


Can't access any of Linq methods

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

How to upgrade mvc2 to mvc5?,,

Paging in .NET Web API

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