The Light
The Light

Reputation: 27011

How to find out part of the url from within a Web API Action?

In Web API, I have a UserController inside which there is an action as below:

[HttpGet]
public string SearchByEmail(string email)
{
    // how to get the sitename?
    return email;
}

I've added a Route to the WebApiConfig as below:

 config.Routes.MapHttpRoute(
               name: "SearchUserByEmail",
               routeTemplate: "{sitename}/User/SearchByEmail",
               defaults: new
               {
                   controller = "User",
                   action = "SearchByEmail"
               });

basically, the user can call the action using the below path:

/mysitename1/user/[email protected]

How to find out the site name from within the action?

I've written the below method to retrieve it from within my Request:

private string GetSiteName()
        {
            return this.Request.RequestUri.Segments[1].Replace("/", String.Empty);
        }

But isn't there any better way in MVC?

Upvotes: 0

Views: 86

Answers (2)

Kiran
Kiran

Reputation: 57949

you can get the details from the Route Data present on the current request.

Request.GetRouteData().Values["sitename"].ToString()

Upvotes: 0

Jon Susiak
Jon Susiak

Reputation: 4978

Use the following Action in your UserController:

[HttpGet]
public string SearchByEmail([FromUri]string sitename, string email)
{
   //Do stuff with sitename
   return email;
}

Upvotes: 1

Related Questions