Featured post
asp.net - Fallback Route in ASP MVC if action doesn't exist -
the default route in mvc {controller}/{action}/{id}
part quite helpful being able set default if incoming url doesn't include parameter there way specify default action when action doesn't exist on controller?
what want achieve being able have controllers several specific actions , own catchall uses url grab content basic cms.
for example products controller like:
public class productscontroller: controller{ public actionresult productinfo(int id){...} public actionresult addproduct(){...} public actionresult contentfromcms(string url){...} }
where default route handle /products/productinfo/54
etc request url of /products/suppliers/acme
return contentfromcms("suppliers/acme");
(sending url parameter nicer not needed , parameterless method request fine).
currently can think of 2 possible ways achieve this, either:
create new constraint reflects on controller see if have action of given name , use in {controller}/{action}/{id}
route allowing me have more general catchall {controller}/{*url}
.
override handleunknownaction
on controller.
the first approach seems quite roundabout way of checking while second don't know internals of mvc , routing enough know how proceed.
update
there's not been replies thought i'd leave solution incase finds in future or people suggest improvements/better ways
for controllers wanted have own catchall gave them interface
interface ihasdefaultcontroller { public string defaultroutename { get; } system.web.mvc.actionresult defaultaction(); }
i derived controlleractioninvoker , overrode findaction. calls base findaction then, if base returns null , controller impliments interface call findaction again default actionname.
protected override actiondescriptor findaction(controllercontext controllercontext, controllerdescriptor controllerdescriptor, string actionname) { actiondescriptor foundaction = base.findaction(controllercontext, controllerdescriptor, actionname); if (foundaction == null && controllerdescriptor.controllertype.getinterface("kingsweb.controllers.iwikicontroller") != null) { foundaction = base.findaction(controllercontext, controllerdescriptor, "wikipage"); } return foundaction; }
as want parameters routing replace routedata @ start of default actionresult on controller
controllercontext.routedata = url.routecollection[defaultroutename].getroutedata(httpcontext);
you approach quite fine. side-note:
replace
controllerdescriptor.controllertype.getinterface("kingsweb.controllers.iwikicontroller") != null
with
typeof(kingsweb.controllers.iwikicontroller).isassignablefrom(controllerdescriptor.controllertype)
this more strongly-typed way passing in name of interface via string: if change namespace tomorrow?..
- Get link
- X
- Other Apps
Comments
Post a Comment