Routing 如何从Web API操作中找到url的一部分?
在Web API中,我有一个UserController,其中有一个操作,如下所示:Routing 如何从Web API操作中找到url的一部分?,routing,controller,asp.net-web-api,Routing,Controller,Asp.net Web Api,在Web API中,我有一个UserController,其中有一个操作,如下所示: [HttpGet] public string SearchByEmail(string email) { // how to get the sitename? return email; } config.Routes.MapHttpRoute( name: "SearchUserByEmail", routeTemplate:
[HttpGet]
public string SearchByEmail(string email)
{
// how to get the sitename?
return email;
}
config.Routes.MapHttpRoute(
name: "SearchUserByEmail",
routeTemplate: "{sitename}/User/SearchByEmail",
defaults: new
{
controller = "User",
action = "SearchByEmail"
});
我已将路由添加到WebApiConfig,如下所示:
[HttpGet]
public string SearchByEmail(string email)
{
// how to get the sitename?
return email;
}
config.Routes.MapHttpRoute(
name: "SearchUserByEmail",
routeTemplate: "{sitename}/User/SearchByEmail",
defaults: new
{
controller = "User",
action = "SearchByEmail"
});
基本上,用户可以使用以下路径调用操作:
/mysitename1/user/searchbyemail?email=lala@lala.com
如何从操作中查找站点名称
我编写了以下方法,从我的请求中检索它:
private string GetSiteName()
{
return this.Request.RequestUri.Segments[1].Replace("/", String.Empty);
}
但是在MVC中没有更好的方法吗?在UserController中使用以下操作:
[HttpGet]
public string SearchByEmail([FromUri]string sitename, string email)
{
//Do stuff with sitename
return email;
}
您可以从当前请求中存在的路由数据中获取详细信息
Request.GetRouteData().Values[“sitename”]。ToString()严格来说,[FromUri]属性不是必需的,没有它上面的操作仍然可以工作。