Yii Rest api url manager - api

I am not able to find the logic behind the url manager. Can any body tell me about the given url calling in Rest pattern. I have too many get methods in my Controller with single parameter.
This is my Original url : localhost/project/api/event/getevent/event_id/1
api is Module
event is Controller
getevent is Controller action name
event_id is parameter 1
I want to convert this to Rest pattern localhst/project/api/event/1
//Updated code..
all are related to same Model..............
//Search by Event id
public function actionByEventId(){
$model->byEventId();
}
//Retrieve user's events by User id
public function actionByUserId()
{
$model->userEvents();
}
//Search for event by code
public function actionByEventcode()
{
$model->byEventCode();
}

Add this rule:
'api/<controller:\w+>/<action:\w+>/<id:\d+>' => 'api/<controller>/by<action>'
And add the $id your actions:
public function actionByEventId($id) {
}
public function actionByUserId($id) {
}
Now if you call localhst/project/api/event/eventid/1 Yii will call the actionByEventId in your event-Controller with $id as 1

Related

In ASP.NET Core, is it possible to generate a URI in the controller for a Get action that takes two parameters? If so how?

I have an association controller called ConnectionManagerCategoriesController. It has two Get methods on it. One to get all Categories for a ConnectionManager and one to only retrieve one Categoy for the ConnectionManager based upon the name. I have a Post to create a new category and I am trying to generate a uri for LinkGenerator. However when the URI that is created, it uses the GetConnectionManagerCategories method instead of the GetConnectionManagerCategory. I dont know why or how to do it differently.:
[Route("api/connectionmanagers/{connectionManagerID:int}/categories")]
[ApiController]
public class ConnectionManagerCategoriesController : ControllerBase
{
private readonly LinkGenerator _linkGenerator;
[HttpGet]
public async Task<ActionResult<IEnumerable<ConnectionManagerModel>>> GetConnectionManagerCategoriesAsync(int connectionManagerID){}
[HttpGet("{categoryName}", Name = "GetConnectionManagerCategoryAsync")]
public async Task<ActionResult<ConnectionCategoryModel>> GetConnectionManagerCategoryAsync(int connectionManagerID, string categoryName){}
[HttpPost]
public async Task<ActionResult<ConnectionCategoryModel>> AddConnectionCategoryAsync(int connectionManagerID, string categoryName, [FromHeader(Name = "x-requestid")] string requestId)
{
var url = _linkGenerator.GetUriByRouteValues(HttpContext,
"GetConnectionManagerCategoryAsync",
values: new { connectionManagerID, categoryName = commandResult.CategoryName });
return Created(url, commandResult);
}
It returns the following uri to Swagger: 'http://localhost:6704/api/connectionmanagers/1/categories?categoryName=Almost'
However, when I log the uri in the code it is: http://localhost:6704/api/connectionmanagers/1/categories/newvalueadded
Is this even possible?
You have to show how are trying to run the action, in order to get some explanations. Routing is very tricky and it is better not to try to create routes the way you are creating.
IMHO , it is always a good idea to define the whole route, not just the part. Especially if you use Swager
[HttpGet("{~/api/connectionmanagers/{connectionManagerID:int}/categories/{categoryName}")]
public async Task<ActionResult<ConnectionCategoryModel>> GetConnectionManagerCategoryAsync(int connectionManagerID, string categoryName){}

Call to a member function addUnauthenticatedActions() on null (CakePHP Authentication)

I am trying to implement the CMS Tutorial - Authentication for CakePHP and I am only trying to implement the login page up till now but it is giving me an error on this line
$this->Authentication->addUnauthenticatedActions(['login']);
Error:
Call to a member function addUnauthenticatedActions() on null
UsersController:
public function beforeFilter(\Cake\Event\EventInterface $event){
parent::beforeFilter($event);
// Configure the login action to not require authentication, preventing
// the infinite redirect loop issue
$this->Authentication->addUnauthenticatedActions(['login']);
}
public function initialize() :void{
$this->loadComponent('Flash');
$this->loadComponent('Authentication.Authentication');
}
in your appController use $this->Authentication->addUnauthenticatedActions(['someactions']);
and if you want to use UnauthenticatedActions in your controller you nit to put
public function beforeFilter(EventInterface $event)
{
parent::beforeFilter($event);
$this->Authentication->allowUnauthenticated(['actions']);
}

Route to allow a parameter from both query string and default {id} template

I have an action in my ASP.Net Core WebAPI Controller which takes one parameter. I'm trying to configure it to be able to call it in following forms:
api/{controller}/{action}/{id}
api/{controller}/{action}?id={id}
I can't seem to get the routing right, as I can only make one form to be recognized. The (simplified) action signature looks like this: public ActionResult<string> Get(Guid id). These are the routes I've tried:
[HttpGet("Get")] -- mapped to api/MyController/Get?id=...
[HttpGet("Get/{id}")] -- mapped to api/MyController/Get/...
both of them -- mapped to api/MyController/Get/...
How can I configure my action to be called using both URL forms?
if you want to use route templates
you can provide one in Startup.cs Configure Method Like This:
app.UseMvc(o =>
{
o.MapRoute("main", "{controller}/{action}/{id?}");
});
now you can use both of request addresses.
If you want to use the attribute routing you can use the same way:
[HttpGet("Get/{id?}")]
public async ValueTask<IActionResult> Get(
Guid id)
{
return Ok(id);
}
Make the parameter optional
[Route("api/MyController")]
public class MyController: Controller {
//GET api/MyController/Get
//GET api/MyController/Get/{285A477F-22A7-4691-AA51-08247FB93F7E}
//GET api/MyController/Get?id={285A477F-22A7-4691-AA51-08247FB93F7E}
[HttpGet("Get/{id:guid?}"
public ActionResult<string> Get(Guid? id) {
if(id == null)
return BadRequest();
//...
}
}
This however means that you would need to do some validation of the parameter in the action to account for the fact that it can be passed in as null because of the action being able to accept api/MyController/Get on its own.
Reference Routing to controller actions in ASP.NET Core

LARAVEL 5: Need to keep query string after auth redirects

I have a link I am sending via email. For example, www.swings.com/worker?id=3382&tok=jfli3uf
In this case I want the person to click the link, get sent to the login page(which it does) and then be directed to a controller method WITH the $id and $tok variables. I can't get that part to work. Any ideas? I am only using the RedirectIfAuthenticated class and this is what it looks like:
public function handle($request, Closure $next)
{
$user = $request->user();
if ($this->auth->check()) {
if($user && $user->hasRole('worker'))
{
return redirect('worker');
}
return redirect('home');
}
return $next($request);
}
hasRole is a method I created in the User model that checks the role of the logged in user
You can flash data to the session when redirecting by chaining the with() method:
// in your handle() method:
return redirect('home')->with($request->only('id', 'tok'));
// then in home controller method:
$id = session('id');
$tok = session('tok');
AFTER SOME HOURS I WAS ABLE TO HAVE A SOLUTION:
ReturnIfAuthenticated wasn't changed. I just added the following within my controller that this link should go to:
for instance, the route would be:
Route::get('worker', 'WorkerController#methodINeed');
Within this method:
public function methodINeed() {
$id = Input::get('id');
$tok = Input::get('tok');
// Do what I need this variables to do
}
What I didn't understand and what could not be properly understood is that the auth controller in Laravel 5 is triggered when a user is a guest it will still redirect to the actual method with all its original data once auth is successful. Hope this is helpful.

Using RedirectToAction to break out of a controller/action

In every action in every controller, I would like to have a check that, in certain cases, would return the app to another controller/action. I would like the check to be as simple as possible, something like TestForExit( );
Here's my problem: all my actions return ActionResult, and here is a sample:
public ActionResult Partial()
{
TestForExit( );
...
return PartialView( "ViewPartial", data );
}
If TextForExit returns RedirectToAction( "Index", "Home" ) I have to have something like this:
public ActionResult Partial()
{
var result = TestForExit( );
if( result == null )
{
...
result = PartialView( "ViewPartial", data );
}
return result;
}
But, as I am going to have this everywhere, I'd really like to have TestForExit( ) itself be able to send me to Home/Index rather than return an ActionResult that my Action has to return.
In other words, how can I have TestForExit ACTUALLY go to Home/Index, instead of just returning an ActionResult the the original Action must return?
You will want to use an custom ActionFilter. You can apply this action filter globally. Then in the OnActionExecuting, you can perform the TestForExit check, and redirect if needed.
For example.
public void TestForExitActionFilterAttribute : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(TextForExit())
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {{ "Controller", "ExitController" },
{ "Action", "ExitAction" } });
}
base.OnActionExecuting(filterContext);
}
}
Now apply your [TestForExitActionFilter] attribute to your controllers, or individual actions. Or, to add it everywhere, add the following line to FilterConfig.RegisterGlobalFilters filters.Add(new TextForExitActionFilterAttribute()).
Here are some related links.
Redirecting to specified controller and action in asp.net mvc action filter
http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-custom-action-filters
Alternatively, you can just override the OnActionExecuting method directly in your controller class and add the logic there. This would make more sense than a custom attribute if you only need this exit logic for one particular controller.
Well your controller action method has to return eventually, so you still have to return an ActionResult no matter what if the action is executed.
If you want to avoid adding that code to every action, you could think about creating a custom Action Filter and then marking your actions with that filter, or applying a global filter if you need it for EVERY action.
Then in your action filter, you check your exit condition and redirect if necessary.