WebApi Custom Routing in dotnet Core - .net-core

In dotnet core, I'm trying to create a webapi endpoint that have a value before the controller name.
ex:
template: "api/{AccountId}/[controller]"
endpoint "api/435ABC/Reports/EndOfYear"
I've seen many examples on how to do this in MVC and in Framework 4.x, but not many with WebApi and where I set a parameter before the controller name.

In attribute routing you should change your controller route to [Route("api")] to accept all calls from https://example.com/api.
Note: it will affect all routes inside the Reports controller.
[Route("api")]
public class ReportsController : ApiController
and then decorate your action with route attribute like below:
[Route("{id}/[controller]/[action]")]
this way you can call your action method with https://example.com/api/435ABC/Reports/EndOfYear.
In convention-based routing you should only add route in UseMvc method and remove Route attributes from controller and action:
app.UseMvc(routes =>
{
routes.MapRoute(name: "default", template: "api/{controller=Home}/{action=Index}"); // this line specifies default route
routes.MapRoute(name: "Reports", template: "api/{id}/{controller=Reports}/{action=EndOfYear}"); // this line specifies your custom route
});

Related

web api "get" method results in a view

I have a .net core 2.0 web api with the following get method:
[HttpGet]
public async Task<IEnumerable<Customer>> Get()
{
return await customerDataProvider.GetCustomers();
}
In the startup class i have the following in configuration:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
when i run the application i get the results displayed as raw json in the browser.
I would like to add a view and to handle the results in that view meaning display them in a table and add some filtering and sorting options.
How can i achieve this? I saw different articles on how to add a view or a razor page to a project but none of them was similar to my case..
Thanks!

ASP.NET Core MVC route to controller any child url like "admin/*"

I want to route any url address like /admin/* as my admin is on Angular2 and uses its routing. I tried template: "admin/{*url}"though it works not only with /admin url but with any other. Is there any way to solve this problem?
Add this code in your WebApiConfig.cs file :
config.Routes.MapHttpRoute(
name: "some name",
routeTemplate: "admin/{*url}",
defaults: new { controller = "Admin", action = "Your default action here" });
Set the default controller in defaults.

How to Routes Web API controller Existing Web Form Project

I tried implement web API controller for my existing web form project, i used following code for route my API.
RouteTable.Routes.MapHttpRoute(
name: "EnadocApi",
routeTemplate: "apiv2/{controller}/{action}/{Id}",
defaults: new { Id = RouteParameter.Optional }
);
But it gave following error.
Error
I used VS2015.
The first thing I'd try is to add a reference to System.Web.Http, then add that as a using in your RouteConfig class.
using System.Web.Http;

asp vnext, ignore route

i am using vnext and am using routes, but it routes EVERYTHING.
this is fine (from Startup.cs):
application.UseMvc(routes =>
{
// setup routes
// default mapping
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
but then when i use (in views)
<link href='#Url.Content("~/CDN/r.css")' rel="stylesheet" />
or
<img src="/CDN/i.png" />
it gives a 404 error on those.
so how to set up ignore routes as in the previous versions?
thnx
You should register a StaticFiles middleware before MVC for your case where you want to serve static files like .css, .png etc. So the request for static files would be served by this middleware and would not reach MVC.
// Add static files to the request pipeline.
app.UseStaticFiles();
application.UseMvc(routes =>
{
// setup routes
// default mapping
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
You would need to add the package Microsoft.AspNet.StaticFiles in project.json to get it.

Troubleshooting "The controller for URI is not callable" error

I'm working on Symfony 2.3 and I declared a new route and new controller, but when I call this controller from the browser I get this error:
The controller for URI "/user/1" is not callable. in /dev.mydomain.org/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php at line 82
This is my simple route configuration:
user_homepage:
pattern: /user
defaults: { _controller: UserBundle:Default:index }
user_show:
pattern: /user/{id}
defaults: { _controller: UserBundle:Default:show }
requirements:
id: \d+
And this is my very simple controller:
public function showUserAction($id)
{
return $this->render('UserBundle:Default:show.html.twig', array());
}
What is wrong?
The logical name UserBundle:Default:show refers to UserBunde\Controller\DefaultController::showAction you have a method called showUserAction.
Either change the method name to showAction or change the logical name to UserBundle:Default:showUser.
Although not relevant to the example given, this error can also be caused if the controller Action is not public
You're defining your controller function as showUserAction while in the definition your saying it is show[Action].
Either change your route configuration
user_show:
pattern: /user/{id}
defaults: { _controller: UserBundle:Default:showUser }
requirements:
id: \d+
or change your controller signature
public function showAction($id)
{
See if this helps
After big search, this worked for me:
1.- Create CRUDController
// src/Acme/DemoBundle/Controller/CRUDController.php
namespace Acme\DemoBundle\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Inter\PimeBundle\Entity\Empresa;
class CRUDController extends Controller
{
public function publicarAction($id)
{
//code here...
}
}
2.- Create the service
# app/config/config.yml
services:
ebtity.admin.service:
class: Acme\DemoBundle\Admin\EntityAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: group, label: label }
arguments:
- NULL
- Acme\DemoBundle\Entity\Entity
- AcmeDemoBundle:EntityAdmin
3.- Create the template for the action button
{# src/Acme/DemoBundle/Resources/views/CRUD/list__action_publicar.html.twig #}
<a class="btn btn-sm" href="{{ admin.generateObjectUrl('publicar', object) }}">Publicar</a>
4.- Configure route
// src/Acme/DemoBundle/Admin/EntityAdmin.php
namespace Acme\DemoBundle\Admin;
// ...
use Sonata\AdminBundle\Route\RouteCollection;
class EntityAdmin extends Admin
{
// ...
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('engine')
->add('rescueEngine')
->add('createdAt')
->add('_action', 'actions', array(
'actions' => array(
'publicar' => array(
'template' => 'AcmeDemoBundle:CRUD:list__action_publicar.html.twig'
)
)
));
}
protected function configureRoutes(RouteCollection $collection)
{
$collection
->add('publicar',
$this->getRouterIdParameter().'/publicar',
array('_controller' => 'AcmeDemoBundle:CRUD:publicar')
);
}
}
5.- Clear cache
Hope it helps
Not the case here. But there is another related issue:
If you forget the 'Action' suffix all will work. But when you realized that you forget the suffix and then add it ... surprise! Same error as the OP.
The problem here is about caching
Symfony creates two file for caching urls:
AppDevUrlGenerator.php
AppDevUrlMatcher.php
If you change your action name (i.e. adding 'Action' suffix) then that cache info is obsolete.
Solution
php app/console cache:clear
Similar to the accepted answer, if your controller is defined as a service, e.g. (in YAML):
services:
user.default:
class: \UserBundle\DefaultController
And your route uses this controller service:
user_show:
pattern: /user/{id}
defaults: { _controller: user.default:showUserAction }
requirements:
id: \d+
Then it's necessary to name the action method in full including the Action suffix, otherwise you will get the "controller ... is not callable" error.
In my case, i was using symfony 2.
Prior version of symfony maintain method naming convention. Method suffix should contain Action word.
example:
in route yml file the method definition was
docudex_report_make_authorization:
pattern: /make-authorization
defaults: { _controller: DocudexReportBundle:Default:makeAuthorization }
and in the controller the method was
public function makeAuthorization(){}
therefore i was getting the error.
After changing the method name to public function makeAuthorizationAction it worked perfectly.
I would like to share my experience & how I solved it:
I was importing one bundle in an application whose routes were defined using annotations and they were importing fine in application too by using:
auth_bundle_routes:
# loads routes from the given routing file stored in some bundle
resource: '#XyzAuthBundle/Controller/'
type: annotation
But since my bundle controllers were defined using services, Symfony was showing error:
The controller for URI "/facebook/request-code" is not callable.
Controller Xyz\AuthBundle\Controller\FacebookController" has required
constructor arguments and does not exist in the container. Did you
forget to define such a service?
I updated my bundle for routing to use routing.yaml file over annotations and referring to controllers as service::method syntax and then this error is gone.
xyz_auth.facebook_request_code:
path: /facebook/request-code
controller: xyz_auth.controller.facebook_controller::requestCode
Bundle routes must be imported using
auth_bundle_routes:
resource: '#XyzAuthBundle/Resources/config/routing.yaml'
Hope this will save someone's time.
The same issue could happen if your env uses .env.local.php and new changes are added to env files without running composer dump-env
One of the reasons for this error is that you missed to add the word "Action" after the controller's method name. If you think that your routing is OK, check the method name.

Resources