How can I have controllers with same name but in different folders in Mvc - model-view-controller

I have a controller called CarsController that worked fine, but then I created a subfolder in the controllers folder, named it v1 and added another controller also called CarsController. I cannot call the new controller beacuse I get this error..
Multiple types were found that match the controller named
I thought it would help just adding this...
// V1 Route
config.Routes.MapHttpRoute(
name: "DefaultRouteV1",
routeTemplate: "api/v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
But it did not, how can I solve this?

Related

Visual Studio Web API: How to change the routing path

I am working on Web Api. By default, it uses the api/{controller}/{id} as a url. I am able to have it to route api/device/{controller}/{id} but this will affect to all Web API route to that path.
But I only want certain controller to be in api/device/{controller}/{id} and the rest will go to another path.
I saw something like RoutePrefix but it doesn't seem to work...
[RoutePrefix (api/data/abc)] where abc is the controller name.
Add the custom route mapping in WebApiConfig.cs file before default route map:
By adding this before, any requests which matches the custom route will be executed, else the other one.
config.Routes.MapHttpRoute(
name: "CustomRoute",
routeTemplate: "api/device/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
If you want to customize the routing with a per controller approach, then you have to use Attribute Routing instead of the standard convention-based routing.
Decorate your controllers with RoutePrefix attribute, and your actions with Route attribute in this way:
[RoutePrefix("api/device/mydevice")]
public class MyDeviceController : ApiController {
[Route("{id}")]
[HttpGet]
public IHttpActionResult Get(int id) {
//DoWork
//...
}
}
And remember to enable attribute routing on the HttpConfiguration object:
config.MapHttpAttributeRoutes();
You may also remove MapHttpRoute method calls if you do not want to allow access to your actions in the standard convention-based way.
More on attribute routing on the official documentation.

Calling Web Api un Umbraco 7

I'm trying to call a webapi hosted within the same project as an umbraco website.
I'm using the default webapi routing and calling it in on application start:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
...and set up a controller in an api folder under the controllers folder:
public class ServiceContactFormController : UmbracoApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
}
When I call the webapi using http://localhost:[port]/api/ServiceContactForm I receive a 404.
Are there any additional steps required specifically for Umbraco?
Regards
Never mind - for anyone else out there, Umbraco kindly take over the routing and add 'umbraco' to the route, plus you need the action due to the default get, post, etc methods not being recognised...more info here https://our.umbraco.org/forum/developers/api-questions/39075-Web-API-routing-not-working.
Working example was:
http://localhost:[port]/umbraco/api/ServiceContactForm/get

Adding custom method to WebAPI

I am new to the WebAPI and I got stuck in a problem. I am using API controller which contains two Get methods. One is used for GetAll while other retrieves data on the basis of ID. Now what I want to do is to implement another get method which takes string and returns records. I have made that method and call that it does not work as my route was default API route which was like:
config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
When I added a new route to call my custom GetMethod:
config.Routes.MapHttpRoute(name: "Custom", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
I was able to call my custom GetMethod but now I lose the restful method with id parameters. How can I use both methods?
Have you tried using your second route only and call as
api/customer/get/1
api/customer/getall/
api/customer/getmethod/one
In the above, customer is the controller name. You have to replace with yours.
Please check whether you have the routes in the webapiconfig.cs file. Please refer this article for more help.
Better not to change routes.
You can use Action Name to differentiate the calls and can add more functions. Take a look at this answer:
How to add custom methods to ASP.NET WebAPI controller?

Specify valid controllers for a route

I've to provide two Web API controllers PublicController and PrivateController for our system. These should have the following routes:
/public/{controller}/{id}
and
/private/{controller}/{id}
On the firewall, all requests to /private are blocked and only available from inside the network. But by convention, both of my controllers are available for both routes, so I could request PrivateController (which should only be available under /private) with the url /public/PrivateController/1.
Is there a way to specify valid controllers for a route, so that the PrivateController is only available for the private route? Or are there some other practices to fullfill this requirement?
Thanks for your replies.
You can use the constraints parameter to provide restrictions on the controller name in the simplest case with a very simple regular expression:
config.Routes.MapHttpRoute(
name: "private",
routeTemplate: "api/private/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { controller = #"private" }
);
config.Routes.MapHttpRoute(
name: "public",
routeTemplate: "api/public/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { controller = #"public" }
);
So the now the "private" route only accept the controller which named Private and the "public" route will only accept the controller which named Public. If you have multiple public and private controllers you can easily extend the regex to match them.
If the regex is not enough for your needs you can create your custom route contaraint with implementing the IRouteConstraint interface. You can find an example implantation In this article.

How to do asp.net webapi routing when it comes to custom models?

I am developing an ASP.Net WebApi application and facing some difficulties with routing. I have following code in my WebApi controller.
public class UserRegistrationServiceWebApiController : ApiController
{
[HttpPost]
public void RegisterUser(RegisterUser registerUser)
{
/*Some code here*/
}
[HttpPost]
public void ConfirmUserPassword(UserPasswordConfirmModel userPasswordData)
{
/*Some code here*/
}
}
In my RouteConfig.cs, I have given the routes like this.
routes.MapHttpRoute(
name: "UserRegistrationApi",
routeTemplate: "api/{controller}/{action}/{firstName}/{lastName}/{email}/{phoneNo}/{company}"
);
routes.MapHttpRoute(
name: "UserPasswordConfirmationApi",
routeTemplate: "api/{controller}/{action}/{userId}/{password}"
);
The attributes here (firstName, lastName etc) are getting filled properly from the client-side and I can see them in server-side when I call these two actions separately. But when both actions are in the controller, it says it cannot identify which action to pick. This is obviously because of the custom objects i am filling in the server-side (RegisterUser model and UserPasswordConfirmModel model). So there is a conflict there.
This is because of the routing problem. Appreciate any kind of help.
Thanks in advance.
Actually I found out the problem is with the conflict of two actions in the same controller. If I use these two actions separately they work fine. I do not know how to handle when we have two actions in the same controller like above.
I looked in to custom parameter binding, but I do not think that is the problem since my actions work fine separately.
Thanks.
A short answer, do not have two actions on the same controller. But if you want to, use specific routes (add a constraint). Also, is there a reason to have the password in the url?
routes.MapHttpRoute(
name: "UserRegistrationApi",
routeTemplate: "api/{controller}/{action}/{firstName}/{lastName}/{email}/{phoneNo}/{company}",
constraints = new { action = "RegisterUser" }
);
routes.MapHttpRoute(
name: "UserPasswordConfirmationApi",
routeTemplate: "api/{controller}/{action}/{userId}/{password}",
constraints = new { action = "ConfirmUserPassword" }
);

Resources