This is a long post. I am using attribute routing as described here:
http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#enabling-attribute-routing
I have placed in WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
+ config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
}
in Global.asax.cs
AreaRegistration.RegisterAllAreas();
+ //WebApiConfig.Register(GlobalConfiguration.Configuration);
+ GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
and I am using a webapi controller with:
public class HelloController : ApiController
{
[Route("Services/test/Application/{id}")]
public string GetTest(int id)
{
return "1";
}
}
I am using Postman Chrome extension to test. On my own computer when I test in Visual Studio this is working perfectly: http://localhost:6296/Services/test/Application/12
and returns the expected result, but after I deploy it on a site, it does not work: http://www.mytest.com/Services/test/Application/12 (tested even on the server localhost: http://localhost/Services/test/Application/12)
and returns:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Services/test/Application/12
The reference System.Web.Mvc (version 5.2.3.0) is marked as "copy local = true". No authorization is used. Classic webapi controlls work perfectly on the server and locally.
Question: what could be wrong and where should I start looking?!
Add this to your WebApiConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}
Related
I am pretty new to ASP.NET Website programming. I have an node js express application where I need to make requests to. This currently doesnt works from my asp.net site because i dont have cors enabled. I hope you can help me and if I am just beeing stupid and configured my website wrong or forgot to add a controller please let me know.
I tried adding cors package via nuget and adding it to the web.config.
In the Solution Explorer, expand the WebApi project. Open the file App_Start/WebApiConfig.cs, and add the following code to the method WebApiConfig.Register.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Then add the attribute [EnableCors] to the desired controller:
namespace MyProject.Controllers
{
[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
I'm building a new Web API project from scratch and am unable to get any response other than 404 (Not Found).
The routes for each controller and method are declared in attributes.
Here is my Global.asax Application_Start method.
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
Log.Info("Application_Start...");
GlobalConfiguration.Configure(IoCConfig.Register);
Collaboral.Common.DB.DatabaseUtil.SetRetryStratPol();
GlobalConfiguration.Configuration.EnsureInitialized();
}
That code calls the method IoCConfig.Register.
public static void Register(HttpConfiguration config)
{
config.DependencyResolver = new TinyIocWebApiDependencyResolver(RegisterDependencies());
config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*"));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
foreach (var route in config.Routes)
{
Log.Info($"{nameof(Register)}: Route = \"{route.RouteTemplate}\"");
}
}
As can be seen, I'm logging the routes in the config.Routes collection, and I can see from the log file that this collection contains only the default route which I have manually mapped.
WebApiApplication | - Application_Start...|
IoCConfig | - Register: Route = ""|
IoCConfig | - Register: Route = "api/{controller}/{id}"|
And here is an example of how I've used the routing attributes.
namespace MyApi.Controllers
{
[BasicHttpAuthorize(RequireAuthentication = true)]
[RoutePrefix("v1/projects")]
public class ProjectsController : ApiController
{
[Route("{projectId:guid}/assocs")]
[HttpGet]
[Authorize(Roles = // ...)]
public IHttpActionResult GetAssociations(Guid projectId)
{
// ...
}
The URL I'm attempting is
http://localhost/myapi/v1/projects/bbe89597-28ae-40d5-8071-56dfb222f97b/assocs
Some additional points:
this WebApi project is replacing an older version which has been excluded from the solution. The routes are identical
the project is hosted as an application in IIS. I'm using the same application as the older API but the application's settings (in IIS) point to the local folder for the newer project
What am I missing?
Why you are using 'myapi' in your endpoint? your endpoint should be like
http://localhost/v1/projects/bbe89597-28ae-40d5-8071-56dfb222f97b/assocs
You can refer this link for more information.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm creating a rest api in visual studio express 2013.
I have 2 controllers: one for orders and one for clients.
I've already created the following:
/api/clients GET information about all clients
/api/clients/1 GET information about client with id = 1
/api/orders/10 GET information about order with id = 10
Now, I want to create this:
/api/clients/1/orders - GET information about all orders of client with id 1
I've read about attribute routing, but I can't make it work.
OrdersController.cs
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OrdersController : ApiController
{
public Order Get(string id)
{
// ...
}
[Route("clients/{id}/orders")]
public List<Order> GetByClient(string id)
{
// ...
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable CORS
config.EnableCors();
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Like this, all of the other requests work properly, but when I try to access /api/clients/1/orders, I get the error HTTP Error 404.0 - Not Found. The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
But as soon as I uncomment config.MapHttpAttributeRoutes();, I'm no longer able to access any of the requests - they all return this:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>
What am I doing wrong here?
With routing attribute [Route("clients/{id}/orders")], you should access action GetByClient() not by /api/clients/1/orders url, but with /clients/1/orders. To have an original url just fix the routing:
[Route("api/clients/{id}/orders")]
public List<Order> GetByClient(string id)
Uncomment your config.MapHttpAttributeRoutes() line, then in your Global.asax file, replace this:
WebApiConfig.Register(GlobalConfiguration.Configuration);
with this:
GlobalConfiguration.Configure(WebApiConfig.Register);
You can read about it here:
Attribute Routing in ASP.NET Web API 2
I have ASP MVC 4 project and the Web API.
I wanna use Web API from the main application. i did this:
WebAPI Project
WebApiConfig.cs
public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));
}
Global.asax
protected void Application_Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
}
StatisticsController.cs
public class StatisticsController : ApiController {
TopUserFactory topUserFactory = new TopUserFactory();
// GET api/statistics/topUsers
[ActionName("topUsers")]
public List<TopUser> Get() {
return topUserFactory.Top10Users();
}
}
But nothing happens when i go for localhost:31003/api/statistics/{topUsers}
How to use WebAPI project from other project?
When working with multiple sites locally they will have different port numbers.
You can check the port numbers by clicking the IIS Express icon on your taskbar:
You can change the port number by adding a configuration:
Changing project port number in Visual Studio 2013
your code looks ok. it's very easy to get the routes wrong with WebAPI, ensure you're doing a parameter-less GET to http://localhost:31003/api/statistics/topUsers
failing that, use this tool: https://www.nuget.org/packages/routedebugger/
There's a great thread running here:
How to add Web API to an existing ASP.NET MVC (5) Web Application project?
Unfortunately, for me is having an error on WebApiConfig in Global.asax, so how can i fix this error i even installed nugets.
The name 'WebApiConfig' does not exist in the current context
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
WebApiConfig
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// WebAPI when dealing with JSON & JavaScript!
// Setup json serialization to serialize classes to camel (std. Json format)
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}
As you copied code from other project , you are merging web api in existing mvc project so many time two project have different namespace so you have to add namespace or change namespace of webapiconfig.