This is my route configuration:
config.Routes.MapHttpRoute(
name: "Public",
routeTemplate: "{dept}/{unit}/",
defaults: new
{
controller = "Home",
action = "Index"
},
constraints: new { constraint = new MyConstraint() }
);
When I type into the url:
mysite.com/XYZ/123
then my constraint class is triggered
but when I use:
mysite.com/XYZ/123/ with the appended slash the constraint class is not triggered.
I use Web Api 2.
In the routeTemplate I can use the "/" at the end or not that doesnt make difference.
Why does it not work?
UPDATE
public class HomeController : ApiController
{
[HttpGet]
public HttpResponseMessage Index()
{
}
}
I've updated my answer:
Try attribute routing:
[RoutePrefix("dept")]
public class DepartmentController : ApiController
{
[Route("unit:int:min(1)"}]
public object Unit() {}
}
Constraints can be setup like above. More:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints
Related
I just want to customize routes in asp.net mvc ,
This is a blog website and I want to access controller methods using
wwww.sitename.com/blog/{blogtitle}
www.sitename.com/blog/{action}
Blog Controller
public class BlogController : Controller
{
public ActionResult Index(string title)
{
return View();
}
[Route("post-blog")]
[HttpPost]
public ActionResult Post(Blog blog,HttpPostedFileBase blogimage)
{
//some coe
}
[Route("post-blog")]
public ActionResult Post()
{
if (Request.Cookies["userInfo"]==null)
{
return Redirect("/login");
}
return View();
}
}
Here is route Config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.Canonicalize().Www();
routes.Canonicalize().Lowercase();
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "freelogomaker", id = UrlParameter.Optional }
);
}
But I am unable to hit action name "Index" using www.site.com/blog/titlename
But I can access "post-blog" using www.site.com/blog/post-blog
Please help me I am beginner in asp.net mvc routing.
Add your parameter to the route attribute within {} brackets to indicate that it should be read from the URL, and not from something else (such as POST body, dependency injections, etc)
[Route("{title}")]
public ActionResult Index(string title)
{
return View();
}
I also like to add the RoutePrefix attribute to the controller to make it a bit clearer.
[RoutePrefix("blog")]
public class BlogController : Controller
I have a Asp.Net webApi controller as below:
[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{
[Route("GetDetails/{id}")]
public HttpResponseMessage Get(string id)
{
// get business details code.
}
}
Is there anyway that client can hit this api with id null??
It depends on your configuration of Web API routes in App_Start/WebApiConfig.cs.
If route is something like:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "business/api/v1/GetDetails/{id}",
defaults: new { id = RouteParameter.Optional }
);
then user can reach resource use http://localhost.business/api/v1/GetDetails or http://localhost.business/api/v1/GetDetails/1.
When you remove defaults: new { id = RouteParameter.Optional } then user have to pass an id otherwise, it will return 404
Please try:
[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{
[Route("GetDetails/{id:int?}")]
public HttpResponseMessage Get(int id)
{
// get business details code.
}
}
I'm using attribute routing with Web API, and everything works as expected if I request the URL /myapi/list with the following controller:
[RoutePrefix("myapi")]
public class MyController : ApiController
{
[HttpGet]
[Route("list")]
public async Task<string> Get()
{
// Return result
}
}
However, I would like my Get() method to be the default, i.e. when requesting the URL /myapi (without the /list part).
But if I remove the "list" part of the Route attribute like so...
[RoutePrefix("myapi")]
public class MyController : ApiController
{
[HttpGet]
[Route] // Default route
public async Task<string> Get()
{
// Return result
}
}
...I get a 403.14 error saying
"The Web server is configured to not list the contents of this
directory."
Any ideas of what might be causing this?
Thanks!
Edit: If I request the API controller using the default route pattern like /api/myapi, it maps to the Get() method as expected.
Default route is registered after the attribute routes:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Use
[Route("")]
for the default route
[RoutePrefix("myapi")]
public class MyController : ApiController
{
//GET myapi
[HttpGet]
[Route("")] // Default route
public async Task<string> Get() { ... }
}
Reference: Attribute Routing in ASP.NET Web API 2 : Route Prefixes
As pointed out by haim770 in the comments: the problem was that I had a physical folder with the same name as the route prefix.
Renaming either the folder or the route prefix solved the problem.
I guess an alternative would have been to tweak the route/handler order to ensure attribute routes take precedence over physical paths.
I created a web service using WEB API.
I'm using this routing configuration
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
And my solution include two controller (ProductController and DetailController)
So when I want to call a WS that refers to the GetDetails method(is located inside DetailController) I have to use a URL like this:
http://localhost/api/Details/GetDetails/?id=4
Is there a way for use, for the same request, this URL instead:
http://localhost/api/Product/GetDetails/?id=4
letting the GetDetails method inside the DetailController?
Actually your urls should be:
http://localhost/api/Details/4
http://localhost/api/Products/4
and your controllers:
public class DetailsController: ApiController
{
public HttpResponseMessage Get(int id)
{
...
}
}
and:
public class ProductsController: ApiController
{
public HttpResponseMessage Get(int id)
{
...
}
}
Now that's RESTful.
I have the default Route in Global.asax:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
I wanted to be able to target a specific function, so I created another route:
RouteTable.Routes.MapHttpRoute(
name: "WithActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
So, in my controller, I have:
public string Get(int id)
{
return "object of id id";
}
[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
return new string[] { "byCategory1", "byCategory2" };
}
Calling .../api/records/bycategoryid/5 will give me what I want.
However, calling .../api/records/1 will give me the error
Multiple actions were found that match the request: ...
I understand why that is - the routes just define what URLs are valid, but when it comes to function matching, both Get(int id) and ByCategoryId(int id) match api/{controller}/{id}, which is what confuses the framework.
What do I need to do to get the default API route to work again, and keep the one with {action}? I thought of creating a different controller named RecordByCategoryIdController to match the default API route, for which I would request .../api/recordbycategoryid/5. However, I find that to be a "dirty" (thus unsatisfactory) solution. I've looked for answers on this and no tutorial out there on using a route with {action} even mentions this issue.
The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.
So, you should:
Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".
Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".
Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.
So your route should like this:
// Map this rule first
RouteTable.Routes.MapRoute(
"WithActionApi",
"api/{controller}/{action}/{id}"
);
RouteTable.Routes.MapRoute(
"DefaultApi",
"api/{controller}/{id}",
new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);
And your controller:
[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
return "object of id id";
}
[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
return new string[] { "byCategory1", "byCategory2" };
}
You can solve your problem with help of Attribute routing
Controller
[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }
URI in jquery
api/category/1
Route Configuration
using System.Web.Http;
namespace WebApplication
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
}
and your default routing is working as default convention-based routing
Controller
public string Get(int id)
{
return "object of id id";
}
URI in Jquery
/api/records/1
Route Configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Review article for more information Attribute routing and onvention-based routing here & this
Try this.
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var json = config.Formatters.JsonFormatter;
json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }
);
}
}
The possible reason can also be that you have not inherited Controller from ApiController.
Happened with me took a while to understand the same.
To differentiate the routes, try adding a constraint that id must be numeric:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
constraints: new { id = #"\d+" }, // Only matches if "id" is one or more digits.
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);