Mohamad Mustafa
Mohamad Mustafa

Reputation: 65

Asp.NET Core Path string

I'm working in Asp.NET Core in VS 2015.

I'm trying to get the last directory in a URL.

I'm currently using string path = Context.Request.Path; which, for example, if I had the URL localhost.foo.com/bar/3, it would return /bar/3, Is there a way to get the 3 only? The 3 would be an ID for an object in my case.

And if not, is there a better way to return an object's ID that's used in the URL?

Upvotes: 0

Views: 11320

Answers (2)

Backs
Backs

Reputation: 24913

You can split your string by / and get last element:

string path = Context.Request.Path;
var lastValue = path.Split('/').Last();

Upvotes: 2

Josh Knack
Josh Knack

Reputation: 405

You should be using route parameters in order to do this:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing

If you have the following code:

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");

your controller function could take in a parameter like:

public IHttpActionResult myFunc(int id)

If this route template does not fit your exact situation, you could add additional route templates so that the parameters are mapped, or you could add a custom route to the attributes on your function to get the parameters you're looking for.

Upvotes: 2

Related Questions