I'm having a problem getting UriPathExtensionMapping working in ASP.NET WebAPI. My setup is as follows:
My routes are:
config.Routes.MapHttpRoute(
name: "Api UriPathExtension",
routeTemplate: "api/{controller}.{extension}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Api UriPathExtension ID",
routeTemplate: "api/{controller}/{id}.{extension}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
My Global ASAX file is:
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
My Controller is:
public IEnumerable<string> Get()
{
return new string[] { "Box", "Rectangle" };
}
// GET /api/values/5
public string Get(int id)
{
return "Box";
}
// POST /api/values
public void Post(string value)
{
}
// PUT /api/values/5
public void Put(int id, string value)
{
}
// DELETE /api/values/5
public void Delete(int id)
{
}
When making requests using curl, JSON is the default response, even when I explicitly request XML I still get JSON:
curl http://localhost/eco/api/products/5.xml
Returns:
"http://www.google.com"
Can anyone see the problem with my setup?
The following code maps the extensions in the Global.asax file after the routes have been configured:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.
MediaTypeMappings.Add(
new UriPathExtensionMapping(
"json", "application/json"
)
);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.
MediaTypeMappings.Add(
new UriPathExtensionMapping(
"xml", "application/xml"
)
);
Do you need to register the extension mapping like so:
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("json", "application/json"));
config.Formatters.XmlFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("xml", "application/xml"));
Example was found here.
Update
If you look at the code for UriPathExtensionMapping the placeholder for the extension is
/// <summary>
/// The <see cref="T:System.Uri"/> path extension key.
/// </summary>
public static readonly string UriPathExtensionKey = "ext";
So your routes would need to be changed to ({ext} not {extension}):
config.Routes.MapHttpRoute(
name: "Api UriPathExtension",
routeTemplate: "api/{controller}.{ext}/{id}",
defaults: new { id = RouteParameter.Optional }
);
As an addendum to this answer, because I can't comment yet, you should also make sure your web.config contains the line
<modules runAllManagedModulesForAllRequests="true" />
inside the <system.webServer> section.
Mine didn't and this example didn't work for me until I added that line.
Related
I have a post http without header URI parameters, in the image you can see API
When i call it I get the error
No HTTP resource was found that matches the request URI
I'm trying to add a custom route as this in the config file
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: null,
constraints: new { action = "accettaTickets" }
);
because the default needs a URI parameter
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
but I get the same error.
Can you help me?
Thanks!
I suppose you don't have controller with proper action method for this URL. Try to add such controller with default route configuration.
public class WATicketController : ApiController
{
public IEnumerable<string> accettaTickets()
{
return new string[] { "value1", "value2" };
}
}
In MVC WEB API using C# and .Net framework 4.5.1 I have a controller name MonitoringController as bellow:
public class MonitoringController : ApiController
{
[HttpGet]
[ActionName("list")]
public IEnumerable<string> List(string collection)
{
return new String[] { "test 1", "test 2" };
}
}
and my routing config is like this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MapHttpAttributeRoutes();
config.EnsureInitialized();
The api works fine on get requests e.g. http://localhost/api/monitoring/list?collection=test
How do I apply Route attribute to make sure it works on http://localhost/api/monitoring/channels/list?collection=test
What I thought I should do was :
[RoutePrefix("api/monitoring")]
public class MonitoringController : ApiController
{
[HttpGet]
[Route("channels")]
[ActionName("list")]
public IEnumerable<string> List(string collection)
{
return new String[] { "test 1", "test 2" };
}
}
I cannot get http://localhost/api/monitoring/channels/list?collection=test working! What have I done wrong?
I want to be able to have the following routes defined in the controller:
/api/monitoring/channels/list
/api/monitoring/windows/list
/api/monitoring/doors/list
Thanks for your help
Try flipping the order in which you register the routes:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
And also change [Route("channels")] to [Route("channels/list")] and dump the ActionName attribute.
Better still, don't mix the two approaches and go attribute routing throughout.
If you want the collection to be part of the route use a route parameter.
[Route("{collection}/list")]
See http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
I am trying to selfthost web API using OWIN by following the below link
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
But, during the execution of this below line
using (WebApp.Start<SelfHostStartup>(url: baseAddress))
I am getting EntryPointNotFoundException as MyNamespace.SelfHostStartup was not found in assembly.
any help would be appreciated.
Thank you.
public class SelfHostStartup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
var config = new HttpConfiguration();
// Loads external library's (that contain the web api controllers) into the web api self host system
var assemblyResolver = new SelfHostAssemblyResolver();
config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);
// Creates the IoC Container & mounts to Web API
config.DependencyResolver =
new AutofacWebApiDependencyResolver(Framework.Infastructure.Dependency.AutofacContainer.Container);
config.Services.Add(typeof(IExceptionLogger), new MyNamespace.ApiExceptionLogger(Framework.Infastructure.Dependency.AutofacContainer.Resolve<ILogger>()));
// Configures Web API Controller Routing
RouteConfig(config);
config.EnsureInitialized();
// Tells OWIN self host to use this configuration
appBuilder.UseWebApi(config);
}
/// <summary>
/// Configuration of the Routing for the Web API Controllers
/// </summary>
/// <param name="config"></param>
private void RouteConfig(HttpConfiguration config)
{
#if DEBUG
//Enabling Cors Globally
config.EnableCors(new EnableCorsAttribute("http://localhost:60279", "*", "*"));
#else
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
#endif
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "Core",
routeTemplate: "api/core/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Domain",
routeTemplate: "api/domain/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Domain1",
routeTemplate: "api/domain/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I have this requirement to map the url
api/v1/Contact/12/tags
in the above url the Contact is the controller, and 12 is the contactId and tags is the action is want to be called.
The method is like this
[HttpGet]
public List<TagModel> Tags([FromUri]int contactId)
I have did like this
config.Routes.MapHttpRoute(
name: "RouteForHandlingTags",
routeTemplate: "api/v1/{controller}/{id}/{action}",
defaults: new { },
constraints: new { id = #"\d+" }
);
I am getting the error "No HTTP resource was found that matches the request URI http://localhost:4837/api/v1/contact/12/tags"
I have tried
[HttpGet]
public List<TagModel> Tags(int contactId)
and
config.Routes.MapHttpRoute(
name: "RouteForHandlingTags",
routeTemplate: "api/v1/{controller}/{id}/{action}"
);
But all are giving the same error. But when I do a call like this
api/v1/Contact/12/tags?contactid=12
everything works fine. But this is not what I want. The contactId is specified after contact. Can anyone please tell me how to route this?
The parameter names in your action and route must match.
You can either change your action to:
[HttpGet]
public List<TagModel> Tags(int id)
Or change your route to:
config.Routes.MapHttpRoute(
name: "RouteForHandlingTags",
routeTemplate: "api/v1/{controller}/{contactId}/{action}",
defaults: new { },
constraints: new { id = #"\d+" }
);
Note: you do not need [FromUri] with a primitive type like an int.
I try to something on Web Api. First I will share my WebApiConfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiCategory",
routeTemplate: "api/tales/{category}/{id}",
defaults: new { controller = "Tales", id = RouteParameter.Optional},
constraints: new { category = #"^[a-z]+$" }
);
I read this issue and I fix my apiconfig file. My purpose like this:
List GetAllTales() = api/tales/ -> 404 Not Found
Tale GetTale(int id) = api/tales/1 -> Ok!
List GetAllTalesByCategory(string categoryName) = api/tales/kids -> Ok!
Tale GetTalesByCategoryAndId(string categoryName, int id) = api/tales/kids/1 -> Ok!
İf u wonder my ApiController
[HttpGet]
public Tale GetAllTalesByCategoryAndId(string category, int id){}
[HttpGet]
public IEnumerable<Tale> GetAllTalesByCategory(string category){}
[HttpGet]
public IEnumerable<Tale> GetAllTales(){}
[HttpGet]
public Tale GetTale(int id){}
Thanks for all replies.
You need to switch the route order. Default route will handle the request when you don't specify an id (api/tales) so you need to place your custom route before that.
config.Routes.MapHttpRoute(
name: "ApiCategory",
routeTemplate: "api/tales/{category}/{id}",
defaults: new { controller = "Tales",
id = RouteParameter.Optional,
category = RouteParameter.Optional});
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"^[0-9]+$" }
);