not able to pass value to controller from routes - codeigniter-4

in Codeigneter 4 i have created a method in my controller and then added his route URL in routes.php. its working when I am not trying to receive a parameter but when I want to receive a parameter it gives the error 404 page not found.
My Controller Method
public function ViewProduct($param=1)
{
echo $param;
}
my Routes.php File
$routes->get('product/(:any)', 'Public/Publiccontroller::ViewProduct/$1'); Not Working
but when I add like this its work fine
$routes->get('product', 'Public/Publiccontroller::ViewProduct/'); Working

look t example
query url httpss://exmple.com/home/ViewProduct?age=35
public function ViewProduct($id=1)
{
$age=$_GET['age'];
}
param url httpss://exmple.com/home/ViewProduct/45454
this one receive in function
public function ViewProduct($id=1)
{
echo $id;
}
https://codeigniter.com/user_guide/incoming/routing.html?highlight=route

Related

Angular post to ASP.NET Core 6 gets 400 while Postman works fine

Originally I tried to send the argument as an object, but in ASP.NET Core 6, it is failing (400 error). From the many answers, I decided to stringify the object to a string and pass it like this:
var dtoAsJson: string = JSON.stringify(this.projectCreateInitDto);
this.http.post<ProjectDto>(baseUrl + 'Projects/CreateProject/', dtoAsJson).subscribe({
next: (response: ProjectDto) => {
Stopping on the http.post, dtoAsJson was a text string of course.
The controller looks like this:
[Route("CreateProject")]
[HttpPost("{Jsondto}")]
public async Task<ActionResult<ProjectAPIDto>> CreateProject(string Jsondto)
{
ProjectAPICreateInitDto dto = Json.Decode<ProjectAPICreateInitDto>(Jsondto);
Project project = _mapper.Map<Project>(dto);
}
I stop on the Json.Decode and Jsondto is null.
I've searched for solutions, but I'm stuck.
Thoughts? Thanks in advance
The problem is that you are sending the dtoAsJson-object as the body of the POST request, but in the backend you are trying to receive it as a route parameter.
You could try the following:
[Route("CreateProject")]
[HttpPost]
public async Task<ActionResult<ProjectAPIDto>> CreateProject([FromBody] string Jsondto)
{
ProjectAPICreateInitDto dto = Json.Decode<ProjectAPICreateInitDto>(Jsondto);
Project project = _mapper.Map<Project>(dto);
}
Hint how to further improve your code:
I suppose your code will work without JSON.stringify(), if you use [Route("CreateProject")] and [FromBody] in the backend.

How can I route a path which has '?' character in it in nestjs?

For example in browser we send /controller/test?value=2 but I want to route this at an endpoint? I have another endpoint /controller/test which captures even the requests made to this route
That's a query string.
You can use #Query decorator in the function parameter
#Get('/path')
async find(#Query() query) {
console.log(query);
}
More info
In this situation, it seems like your route /controller/test accepts a query parameter value. Regardless of whether or not you query that route with the query parameter value, all requests will hit your route controller at controller/test.
In other words, your server treats
GET /controller/test as a request to /controller/test as a request with value: undefined
and
GET /controller/test?value=2 as a request to /controller/test as a request with value: 2
Therefore, your controller should look something like (assuming you're using typescript)
interface ControllerQuery {
value?: number
}
#Get('/controller/path')
async controller( #Query query: ControllerQuery ) {
if (query.value) {
console.log(query.value);
} else {
console.log('No value provided, now what?');
}
}
Like said above, query params are not filtered by route. But you could do something like this, which would be more restful as well. That or having a search endpoint.
#Get('/path')
async without() {
console.log('without param');
}
#Get('/path/:value')
async find(#Param('value') value: string,) {
console.log(value);
}
#Get('/path/search')
async search(#Query() query) {
console.log(query);
}

Azure 404 not found when adding new function app to logic app

I have a simple Azure Logic app that is trigger by a new email and then passes the Body to my Function App to remove HTML.
I am getting a 404 not found error and I'm a bit stuck as to what is actually not being found.
I can click on the url and it tells me that my function app is up and running and I've selected the Function App from a list in the Logic App editor.
Are there any log files or something that can provide a bit more information as to what cannot be found?
I think the issue might be that my Function app hasn't published correctly. In VS I am getting a missing trigger attribute but I'm not sure what to add.
Code:
public static class Function1
{
[FunctionName("RemoveHTMLfunction")]
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("HttpWebhook triggered");
string emailBodyContent = await new StreamReader(req.Body).ReadToEndAsync();
String updatedBody = WebUtility.HtmlDecode(RemoveHtmlMarkup(emailBodyContent));
return (ActionResult)new OkObjectResult(new { updatedBody });
}
If you just want to get the body without HTML of the email, you can use Body Preview:
According to the running results, the body obtained by Body has HTML, but Body Preview does not.

Azure function get path of http trigger

I have a http trigger function app which redirects myAPI.com to a version based on the header:
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
var version = req.Headers["x-version"];
if(version.ToString() == "2"){
return new RedirectResult("https://v2.myAPI.com", false);
}
else{
return new RedirectResult("https://v1.myAPI.com", false);
}
}
This works. However if I have a path e.g myAPI.com/customPath it returns 404 for myAPI.com/customPath. I want to redirect to https://v1.myAPI.com/customPath. Thought this would be simple; however I am unable to get the original url from within the function app.
When I try req.Path.Value it gives me /api/HttpTrigger1. How can I get the path or full url of my original post address (myAPI.com/customPath)?
You could use Microsoft.AspNetCore.Http.Extensions.UriHelper.GetEncodedUrl(req) to get the full path. It returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers and other HTTP operations.

Servicestack Display 404 page CatchAllHandlers

Im using servicestack Core with kestrel. I made a CatchAllHandlers delegate with the following code.
var requestType = typeof(NotFoundPage);
var restPath = new RestPath(requestType, pathInfo);
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
But the problem is that my ServicestackApi now is no longer reachable, url: /json/reply/GetApiCall goes to the 404 not found page.
Is there a way to solve this? can i check if its an api call or can i go later in the pipeline to handle the request?
update
I found that if i remove CatchAllHandler and just add the next middleware this middleware is called:
app.Use((context, next) =>
{
context.Response.Body.Write("yaayaya");
return Task.CompletedTask;
});
But this is not what i want, i want to stay inside the servicestack request.
update 2
Looking at the source-code i find HttpHandlerFactory has a property NotFoundHttpHandler Which is filled from the AppHost.
CustomErrorHttpHandlers.Add(HttpStatusCode.NotFound, new PageNotFoundHandler());
The only downside is that i can't provide any request specific information to this Urlhandler, such as the url itself:
public class PageNotFoundHandler : RestHandler
{
public PageNotFoundHandler()
{
var restPath = new RestPath(typeof(Error404), "/Url/For?");
}
}
Trying to make this work but i'm getting stuck on that my RestHandler has different amount of components than the url since this PageNotFoundHandler is made before the RestHandler.
But Basically what im looking for is to Handle a different service/InputDto
I've tried RequestConverters but this code is not reached when CatchAllHandlers doesn't return an Handler. so im stuck in this space in the middle. Anyway i could make all the left over routes, route to a single Dto?
.NET Core's new pipeline programming model expects you to call the next middleware if it wasn't already handled by any of the previously registered middleware which is how .NET Core lets you combine multiple different middlewares into the same App.
Handling Not Found Requests with the last Middleware
The last middleware that's registered will be able to handle any unhandled requests so for instance if you wanted to return a static image for unhandled requests you could register middleware after ServiceStack, e.g:
app.UseServiceStack(new AppHost());
app.Use(new StaticFileHandler("wwwroot/img/404.png"));
Or if you wanted to return a custom 404 page instead:
app.Use(new RazorHandler("/404"));
Which will render the /wwwroot/404.cshtml Razor View with ServiceStack's MVC Razor Views.
This would be the preferred way to handle Not Found requests in .NET Core in which you will be able to register additional middleware after ServiceStack to handle non-ServiceStack requests.
Calling a ServiceStack Service for unhandled requests
If you wanted to call a ServiceStack Service for any unhandled requests you can use a Fallback Route which matches on any request, e.g:
[FallbackRoute("/{Path*}")]
public class Error404
{
public string Path { get; set; }
}
public class UnhandledRequestService : Service
{
public object Any(Error404 request) => ...;
}

Resources