I'm trying to create a link to my WebApi controller using Url.RouterUrl, but I don't know how to add the controller action to it, this is what I have in my view:
var url = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "ClientApi"})';
I want to add the FindClients action to the Url.RouterUrl, I have trying adding action=FindClients, but it produced this url /api/ClientApi?action=FindClients, I need my url to be /api/ClientApi/FindClients
Add the following key to App_Start\WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "Extended",
routeTemplate: "api/{namespace}/{controller}/{action}/{id}",
defaults: new { }
);
As default route do not have {action}
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{namespace}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Then use
#Url.RouteUrl("Extended", new { httproute = "", controller = "ClientApi"})
Related
I am trying to intercept a webapi call but only for a certain controller and am struggling.
I already have a route set up for default management like so:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
and in the same webApiConfig i am assigning a custom handler so I can perform some internal authorisation with the following:
config.MessageHandlers.Add(new CustomAuthorizationHandler());
I now need to be able to send a qebApiRequest through that has the same format as my default but I need to be handled differently for this single controller. Controller is responsible for the resetting of user passwords but my CustomAuthorizationHandler performs logic I want to skip so I though I would create a new PassThruHandler inheriting from DelegateHandler and then create a new route purely for this controller like so:
config.Routes.MapHttpRoute(
name: "PasswordResetApi",
routeTemplate: "{controller}/{id}",
defaults: new { },
constraints: new { controller = #"PasswordReset)" },
handler: new PassThruHandler()
);
but whenever I send my PasswordReset/1234 i still enter the CustomAuthorizationHandler is this not "doable"?
How about applying your custom handler to all controllers except PasswordReset instead of adding it globally to config.MessageHandlers:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: #"^PasswordReset",
handler: new CustomAuthorizationHandler()
);
I have used a constraint to limit this routes to all controllers except PasswordReset for which you could create another route.
I have my WebApiController with name AdminDashBoard.
public class AdminDashBoardController : ApiController
{
[System.Web.Http.AcceptVerbs("GET")]
public HttpResponseMessage GetCaseHistory(string CaseRefId, string token)
{
**Implementation**
}
}
I am able to access API using
Localhost/api/AdminDashBoard/GetCaseHistory?CaseRefId=CTcs004&token=eygk
But i want to access this by custom name such as
Localhost/api/Cases/GetCaseHistory?CaseRefId=CTcs004&token=eygk
I have defined customroutes in my WebApiConfig but it is not working.
config.Routes.MapHttpRoute("CaseHistory", "api/cases/{action}/{CaseRefId}/{token}", defaults: new { controller = "AdminDashBoard", action = "GetCaseHistory", CaseRefId = RouteParameter.Optional, token = RouteParameter.Optional });
the routing you configured will resolve to:
controller => AdminDashBoard
action => GetCaseHistory
But please note that since you've placed /{action} in rout template string, it will affect detection of routing to expect an "action" specified in request URL.
could you try this:
config.Routes.MapHttpRoute("CaseHistory",
"api/Cases/GetCaseHistory",
defaults:
new { controller = "AdminDashBoard",
action = "GetCaseHistory" });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
remember to place your route before default route as default route will capture the request before the customized one.
In addition, you don't need to define parameters "CaseRefId" and "token" in query string into routing, it should be resolved if you have defined correct type in controller method.
Hope this helps.
I'm experimenting setting up a multi-tenant solution in asp.net mvc 4 wherein you are able to specify tenant specific overrides to certain controllers if they require different functionality.
I'd like to have routes that are like
/{Controller}/{Action}/{Id}/
/{Tenant}/{Controller}/{Action}/{Id}
If the tenant isn't specified it should just match the first route.
I have tried
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
name: "Tenant",
url: "{tenant}/{controller}/{action}/{id}",
defaults: new { tenant = "", controller = "Home", action = "Index", id = UrlParameter.Optional });
This works correctly for
/ -> detected as the first route (correct!)
/Home -> detected as
first route (correct!)
/Home/Index -> detected as first route
(correct!)
/Client1/Home/Index - Client1 is detected as controller
name (incorrect)
If I switch the routes around then the tenant route works but the base one does not.
What am I missing here, is it possible to achieve this?
Note, I'd prefer to not have to specify a dummy tenant string in the route as I'll have to translate that back later on in a few places where I need to resolve tenant specific information.
You can use the library I wrote here. This lib allows you to define an alternative route, if the routes conflict. You must define the routes as follows:
var firstRoute = routes.MapReplaceableRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
var secoundRoute = routes.MapRoute(
name: "Tenant",
url: "{tenant}/{controller}/{action}/{id}",
defaults: new { tenant = "", controller = "Home", action = "Index", id =
UrlParameter.Optional }, lookupParameters: new string[] {"tenant"}, lookupService: new LookupService());
firstRoute.AlternativeRoute = secondRoute;
For lookupService, you just need an empty implementation of the IRouteValueLookupService.
I tried to write custom routes.Always i have 404 error what is wrong.I read about routing and did not figure out. I want to display contents like below codes and name must be between a-Z and 0-9.Thanks.
{action}/{name} /details/kll219dkl
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "home", action = "index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "test",
url: "details/{name}",
defaults: new { controller = "Test", action = "Details", name = "ujElk392ow" }
);
and just to showing is working
public ActionResult Details(string name)
{
return Content(name);
}
How about:
routes.MapRoute(
name: "test",
url: "{controller}/details/{name}",
defaults: new { controller = "Test", action = "Details", name = String.Empty },
constraints: new { name = #"^[a-zA-Z0-9]+$" }
);
Which would give you:
Url: Mapped Destination:
/Test/details/kll219dkl TextController->Details(name: "kll219dkl")
In addition to Brad answer. Try to change an order of your routes. Runtime takes first route which fits to request. So routes must be defined from most certain to most general. In your order runtime will always take default route.
I have a controller named ArticleController with an Index method that returns the Article view. This works.
However, I'd like to be able to process any text after Article/ in the URL such as Article/someText Article/fileNanme Article/etc
I thought this would be straightforward by implementing the following:
// GET: /Article/{text}
public ActionResult Index(string someText)
{
...
}
This doesn't work. Any ideas?
Update:
See routes:
routes.MapRoute(
name: "Articles",
url: "Article/{*articleName}",
defaults: new { controller = "Article", action = "Article", id= UrlParameter.Optional }
,
constraints: new { therest = #"\w+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller="Home", action = "Index", id = UrlParameter.Optional }
);
See ArticleController methods:
public ActionResult Index()
{
...
}
public ActionResult Article(string articleName)
{
...
}
You can add a catch-all parameter to the route like this
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{*therest}",
defaults: new { controller = "Home", action = "Index" }
);
Notice the asterisk? This marks therest as a "catch-all" parameter, which will match all remaining segments in the URL.
In your action, you would have
public ActionResult Article(string therest)
{
/*...*/
}
This works even for URLs like "Home/Article/This/Is/The/Rest", in which case therest will have the value "This/Is/The/Rest".
If you want to leave out the controller part of the URL completely, you would have
routes.MapRoute(
name: "Default",
url: "Article/{*therest}",
defaults: new { controller = "Home", action = "Index" }
);
which will match URLs like "Article/ThisIs/JustSomeText".
If you want therest to at least contain something, you might add a routing constraint:
routes.MapRoute(
name: "Default",
url: "Article/{*therest}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { therest = #"\w+" }
);
The constraint is a regular expression that therest must match for the route to match.
Stephen Walther has a nice article on routing and catch-all parameters.
Stephen Walther, again, has an article on routing constraints here.
If you are using standard routing change parameter name from someText to id. Otherwise you have to create custom routing for this parameter
You need to define a route in order to use the url you mentioned. For the latest MVC4, routes file exists in this directory App_Start/RouteConfig.cs
add this new route about the the default route.
routes.MapRoute(
name: "Custom",
url: "Article/{someText}",
defaults: new { controller = "Article", action = "Index" }
);
Try loading your url now. It should work now.