How do I pass a parameter with slash in a ServiceStack route? - c#

My requirement is to pass a value, as a parameter, in a ServiceStack route which includes a slash like this 'SK-LOT-79-14/3/11' so I can fetch the records in my service.
Example route configuration:
[Route("/cims/qcHistoryByLot/{lotNumber}", "GET")]
Example lot number: SK-LOT-79-14/3/11

You simply need to add a * to the end of your route parameter.
[Route("/cims/qcHistoryByLot/{lotNumber*}", "GET")]
public class GetQcHistoryByLot
{
public string LotNumber { get; set; }
}
Using the asterisk * acts as a wildcard and will capture anything after /cims/qcHistoryByLot/ into LotNumber. See wildcard paths in the routing documentation for more information.
This will work for routes where you are passing the slash in the last route parameter. If you require to pass a slash in a parameter that does not come last on the route, then you will need to handle encoding the value. See my other answer here.

Related

HttpGetAttribute Order is ignored

I have two methods in a .net6 web API that I want to expose that have similar routes.
This should not be a problem since one has the keyword ping to identify the route.
But from the looks of it and also from the documentation, the route stops evaluating routes as soon as it finds a match.
As the code runs by default it picks the GetDays method instead of Ping. Most likely because it is found first.
This should be easy to resolve by adding an order to the route.
By default, the route should get order 0 so by setting -1 the Ping route should be evaluated first. And if it does not match try next.
But it does not work. It seems that the Order attribute is ignored and it still picks the GetDays method.
[HttpGet("[controller]/ping", Order = -1)]
public async Task<IActionResult> Ping([FromQuery] string val)
[HttpGet("{from}/{to}")]
public async Task<ActionResult> GetDays(DateTime from, DateTime to)
Anyone have any tips on why the Order attribute is ignored and how to make this work?

string Parameter should allow only alphanumaric and dot in Web api route attribute regular expression in .net c#

I have one method and in webapi, i am using swagger to call web api. In api request 'request type' parameter should allow only alphabets, numbers and dot(.).
i have tried below code but it is not working
[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(string))]
[Route(#"testMethod/{requestType:regex(^[A-Za-z0-9. ]+$)}")]
public IHttpActionResult testMethod(int mid,string requestType = "", )
{
//logic
}
In regular expressions, the dot usually is a placeholder for any character. Thus, you have to escape it. In .NET, this is done with a backslash: A-Za-z0-9\.
This may work :
[a-zA-Z]|\d|\s|\.*

HTTPGET Query String

An URL without a name but it has a value, is that still consider as a query string?
For example:
[HttpGet]
[Route("api/house/{Id}")]
public IActionResult GetHouseById(int Id)
link will be:
http://localhost:44565/api/house/1
Is this still consider a query string?
No, this is part of the path and in RESTful nomenclature is not a query string parameter.
Path variables are required components of the route and MUST be provided in order to identify the appropriate route. Omission of the id parameter when required by a path should cause a 404 (unless another route matches api/house).
Query string parameters however, are optional. They are the last part of the URI and occur after the ? character, such as api/house?id=1. In this style of URI, you might expect the endpoint to return the house that has an id of 1 if the query string parameter is provided, or all houses if it is omitted.
Finally, you would notate a querystring parameter via the FromUri attribute and omitting it from the path:
[HttpGet]
[Route("api/house")]
public IActionResult GetHouseById([FromUri]int id)

ASP.Net MVC Routing Empty Default Parameter

SUMMARY:
I'm reviewing the route mapping for a site I've recently begun work on. I've encountered a route that I'm not familiar with:
RouteTable.Routes.MapRoute(NamedRoutes.ROUTE_NAME, "urlSegment1/urlSegment2", new { });
Notice that the "default" parameter for MapRoute is an empty object. This is normally where I would specify my controller, action, and any parameters. I've been googling around and am finding that I'm not asking the right questions to produce the answer I'm looking for.
QUESTION:
How does MVC routing behave when the "defaults" parameter of MapRoute is an empty object? An answer would be great. Supporting docs would be even better.
EDIT:
The actual route being used is:
routes.MapRoute(NamedRoutes.BROWSE_MEN, "browse/Mens", new { } });
And the problem is occurring when generating the URL using:
Html.BeginForm("Add", "Signup", FormMethod.Post, new { id = "signup", enctype = "multipart/form-data" })
They are mapped as stings and in this case matches everything. The defaults are only there if one of the controller/action parameters are not supplied by the url. In this case no defaults are meaningless. It is actually catching everything string/string.
The route you have there is will match a request that contains exactly the two segments in the url ex. http://localhost/urlSegment1/urlSegment2 and returns a 404. I guess you have this route defined to avoid the following routes handle this request.
When you don't specify a controller, either as URL parameter (token) or default value, you should get an InvalidOperationException:
The matched route does not include a 'controller' route value, which
is required.
Same for action. That is for incoming request. For URL generation there's no requirement for controller or action.
You don't have to specify defaults.
So it works as if there were no default object specified

The ASP.NET MVC Routing Querystring vs Embedded Value Bewilderment

This has probably been asked already - if so sorry! I couldn't find it.
I am unsure as to how asp is able to decide when to use a query string and "normal looking paths" (Embedded values)
Take this for example:
routes.MapRoute(
"SomePage",
"Net/Fix/{value}",
new { controller = "Net", action = "Index" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
I don't know how to explain - I will try.. If I am wrong please explain it
Question 1.
Is the first argument in mapRoute so that we can specify which routing we want to take place when using hyperlinks?
Question 2.
What does the second argument do?
It appears as if the second argument gives you the option of specifying how the routing should occur as below: "Net/Fix/hello" or by specifying placeholders in the form of {controller}/{action}/{somevar}
Question 3:
I assume if nothing is used in question 2 scenario - this specifies default routing that should take place?
Question 4:
How does ASP.NET infer whether to use a query string or an embedded value..
Because for example when I decide to call my page
http:/localhost:portno/Net/Fix/hello
It dutifully prints hello.. but when I do this
http:/localhost:portno/Net/Index/hello
It doesn't work.. unless I do
http:/localhost:portno/Net/Index?value=hello..
Question is... why?!!!
I hope questions were clear.. I will reply to answers (if any later).
The first argument is a route name. Each route should have a unique name, and they can be used for creating links, to assure a link is based on a certain route. It's not important in your case of matching a route.
The second argument is a matching pattern. Literal values are shown in clear, and parameterized values inside curly braces. {}. The parameterized values are not just for specifying the location of a parameter, but also the name of it.
I'm not sure offhand why you would define a route without any matching pattern. Does such an overload of MapRoute() exist?
The reason you get the behavior you do with this url: http:/localhost:portno/Net/Index?value=hello It matches the second (the default) route, not the first.
However, look at the second route pattern:
"{controller}/{action}/{id}"
The controller is the first parameter, action is the second. So with your URL, that request is routed to the Net controller, Index action. the same as your first example.
Because the query string contains a value parameter, that still gets passed to the action method. And it just so happens your action method has a string parameter named value, so it works.

Categories

Resources