ASP.NET MVC WebAPI 404 error - c#

I have an asp.net web forms application running under v4.0 integrated mode.
I tried to add an apicontroller in the App_Code folder.
In the Global.asax, I added the following code
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
When I tried to navigate to the controller at http://localhost/api/Value, I get the 404 error.
The extensionless url is configured in the handler section. I have forms and anonymous authentication enabled for the website.
ExtensionLess url is configured for '*.'
When I hit the url for controller, the request is handled by StaticHandler instead of ExtensionlessUrlHandler-Integrated-4.0.
I have no clue now why the system will throw the error as shown in the image below.

I was experiencing this problem.
I tried editing my WebApiConfig.cs to meet a number of recommendations here and code samples elsewhere. Some worked, but it didn't explain to why the route was not working when WebApiConfig.cs was coded exactly as per the MS template WebApi project.
My actual problem was that in manually adding WebApi to my project, I had not followed the stock order of configuration calls from Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// This is where it "should" be
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// The WebApi routes cannot be initialized here.
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
I could make guesses about why this is, but I didn't investigate further. It wasn't intuitive to say the least.

The problem is in your routing configuration. Mvc routing is different from WebApi routing.
Add reference to System.Web.Http.dll, System.Web.Http.Webhost.dll and System.Net.Http.dll and then configure your API routing as follows:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);

Ensure the following things
1.) Ensure that your IIS is configured with .NET 4.5 or 4.0 if your web api is 4.5 install 4.5 in IIS
run this command in command prompt with administrator privilege
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -i
2.) Change your routing to
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
and make request with Demo/Get (where demo is your controller name)
if the 1,2 are not working try 3
3.) Add following configuration in web.config file
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

Also, make sure your controller ends in the name "Controller" as in "PizzaPieController".

I tried all of the above and had the same problem. It turned out that the App pool created in IIS defaulted to .net 2.0. When I changed it to 4.0 then it worked again

Thanks Shannon, works great =>
My order in my Global.asax was :
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
instead of the good one :
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);

Also try to delete your entire api bin folder's content. Mine was containing old dlls (due to a big namespace renaming) exposing conflicting controllers. Those dll weren't deleted by Visual Studio's Clean functionality.
(However, I find asp.net web api seriously lacks routing and debugging information at the debugging level).

If you create the controller in App_Code how does the routing table know where it is? You have specified the route as "api/{controller/..." but that's not where the controller is located. Try moving it into the correct folder.

After hours of spending time on this , i found the solution to this in my case.
It was the order of registering the Routes in RouteConfig .
We should be registering the HttpRoute in the Route table before the Default controller route . It should be as follows. Route Config Route table configuration
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

Thanks to Shannon, ceinpap, and Shri Guru, the following modification works for me:
WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
...
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Global.asax.cs:
protected void Application_Start()
{
...
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
...
}

For the URL you've trying (http://localhost/api/Value) make sure there's a public type named ValueController which derives from ApiController and has a public method with some of these characteristics:
Method name starts with Get (e.g. GetValues or simply Get).
There's an HttpGet attribute applied to the method.
In case you're trying the code from the default Web API project template, the name of the controller is ValuesController, not ValueController so the URL will be http://localhost/api/values.
If non of the above helps, you may want to enable tracing which can give you a useful insight on where in the pipeline the error occurs (as well as why).
Hope this helps.

None of solutions above solved my problem... My error was that I copied the bin files directly to production server, and then, I don't work. The 404 was gone when I publish the project to disk and copied the "published" folder to server. It's a little obvious, but, can help some one.

I copied a RouteAttribute based controller dll into the bin folder, but it wasn't getting recognized as a valid controller and I was getting the 404 error on the client.
After much debugging, I found my problem. It was because the version of System.Web.Http.dll that the controller was referencing was different from the version of System.Web.Http.dll that the main project (the one containing global.asax.cs) was referencing.
Asp.Net finds the controller by reflection using code like this
internal static bool IsControllerType(Type t)
{
return
t != null &&
t.IsClass &&
t.IsVisible &&
!t.IsAbstract &&
typeof(IHttpController).IsAssignableFrom(t) &&
HasValidControllerName(t);
}
Since IHttpController is different for each version of System.Web.Http.dll, the controller and the main project have to have the same reference.

We had this as well, changing .NET version from 4.5 to 4.5.1 or newer solved the issue

The sequence of registering the route, was the issue in my Application_Start().
the sequence which worked for me was
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
earlier it was
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);

Try just using the Value part of the controller name, like this:
http://localhost/api/Value
Note: By convention, the routing engine will take a value passed as a controller name and append the word Controller to it. By putting ValueController in the URI, you were having the routing engine look for a class named ValueControllerController, which it did not find.

Your route configuration looks good. Double check the handlers section in web.config, for integrated mode this is the proper way to use ExtensionLessUrlHandler:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
More on this topic:
http://blogs.msdn.com/b/tmarq/archive/2010/05/26/how-extensionless-urls-are-handled-by-asp-net-v4.aspx

Time for me to add my silly oversight to the list here: I mistyped my webapi default route path.
Original:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/id",
defaults: new { id = RouteParameter.Optional}
);
Fixed: (observe the curly braces around "id")
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional}
);

I appreciate this is a very old question but I thought I would add another answer for future users.
I found this to happen just now in a project I was working on only after it was deployed to CI/Staging. The solution was to toggle the compilation debug="true" value back and forth while deploying each version to each environment once, and it would fix itself for me.

In my case I forgot to make it derive from ApiController.
So it would look like
public class ValuesController : ApiController

Related

Web Api Route Config ASP-NET MVC

We are developing an ASP.NET MVC application, and we decide separate our API Services/Controllers inside a folder named for example API_Services instead put them directly in the controllers.
The problem is: how we set/define the route for that? Tipically is like the following code (at App_Start folder and WebApiConfig.cs file) :
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
We try set the routeTemplate like:
routeTemplate: "API_Services/api/{controller}/{id}",
Or this:
routeTemplate: "api/API_Services/{controller}/{id}",
Doesn't work... someone can help us? Thank you!
If I understand the question right:
if you use some web api controllers I would recommend to read the book "ASP.NET Web API 2: Building a REST Service from Start to Finish 2nd Edition By Jamie Kurtz , Brian Wortman". There is the chapter about api versions and the author describes routing through folders (V1 folder, V2 etc).
Also You can use just "inline-attribute" routing.
And You can read about Areas (or just try to put some "namespaces" into the routing settings or play with it ). I hope it helps, sorry for my English.
We are strucure like this:
Controllers (Folder)
A_Controller
B_Controller
API (Folder)
A_Controller
B_Controller
After a lot of google search, I found this:
Controllers (Folder)
A_Controller
B_Controller
API (Folder)
A_Controller
B_Controller
(which apparently works, but just tomorrow I go can test and then I give feedback. Anyway thanks for other solutions. Thank you!)
The changes you are talking about are to your folders, not the routes, which the conventions will ignore.
The way it works means that whatever project folder you move it into, if it is named XXXController it will be found without route changes. So with the following this:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
http://yoursite.com/api/XXXController will still find your controller even if it is in another folder:
You can play around with defaults if you want more control but I don't think this is what you are asking for. For example:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/API_services/{id}",
defaults: new { controller="mycontroller" id = RouteParameter.Optional }
So whenever people visit http://yoursite.com/api/API_services, the controller used would be "mycontroller".

ASP.Net MVC IdentityServer3 broke my webapi routing

So I am currently implementing security on a project I am working on and I followed the guide for identityServer3 to add it to my mvc5 application. I got through the complete setup and thought everything was good, until I realized that routes in my api, unless they were the very basic ones, /api/.../ no longer work.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I am using the default routing, and on the various pieces of my api controllers I have put route attributes to guide them in the event they fall outside of this format. for example:
[Route("api/Location/GetByAreaIncludeFileStore/{id}")]
public IEnumerable<Location> GetLocationsByAreaIdIncludeFileStore(int id)
{
if (id <= 0)
{
return null;
}
IEnumerable<Location> locations = _lookupService.GetLocationsByAreaIdIncludesFileStore(id);
return locations;
}
and as i said earlier, prior to adding identity server theses worked beautifully. During the addition of IdentityServer I had to add a few nuget packages to my webapi:
install-package Microsoft.Owin.Host.SystemWeb
install-package Microsoft.Aspnet.WebApi.Owin
install-package Thinktecture.IdentityServer3.AccessTokenValidation
So basically my question after all is said and done is, How can I fix my routes so I can get all of the information I need?
Currently I have routes that are
api/controller
api/controller/id
api/controller/action
api/controller/action/id
Any Help would be amazing, Thanks!
Also, I looked through many of the other posts and tried a lot of variations of routing and attributes before asking this question.
Add this line in your WebApiConfig config.MapHttpAttributeRoutes(); before your config.Routes.MapHttpRoute().
I was actually able to get it working using the method described in the solution in this post: MVC 4.5 Web API Routing not working?
I tried doing this yesterday, and it didn't seem correct, but with a little more spit and polish I ended up achieving proper routes. They recommended having the route config as follows:
config.Routes.MapHttpRoute(
name : "DefaultAPi",
routeTemplate : "api/{controller}/{id}/{action}",
defaults: new {id= RouteParameter.Optional,
action = "DefaultAction"
);
and then following that pattern change all the basic routes like:
[ActionName("DefaultAction")
public string Get()
{
}
[ActionName("SpaceTypes")]
public string GetSpaceTypes(int id)
{
}
It worked, I had to refactor all of my api calls and my restful services to match, but nonetheless, I am back to functioning.

A route named 'MS_attributerouteWebApi' is already in the route collection

I recently added Microsoft.AspNet.WebApi.WebHost to a MVC WebAPI project which would allow me to use the [Route("api/some-action")] attribute on my action. I solved some errors using this article but can't solve the third error below. Added solved errors below to get feedback if I did anything wrong.
First Error: No action was found on the controller 'X' that matches the name 'some-action'
Solution: Added config.MapHttpAttributeRoutes(); to WebApiConfig.cs Register method.
Second Error: System.InvalidOperationException The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
Solution: Added GlobalConfiguration.Configure(WebApiConfig.Register); to Global.asax.cs Application_Start
Third Error: System.ArgumentException: A route named 'MS_attributerouteWebApi' is already in the route collection. Route names must be unique.
Solution = ?
I've already tried cleaning and deleting all DLLs from bin folder according to this post.
I had a similar problem and it was related to a copy paste error on my part where I added a copy of this line in my WebApiConfig.cs file:
config.MapHttpAttributeRoutes();
make sure you only have one of these.
In the Global.asax, check how many times WebApiConfig.Register function has been called.
Solved! Removed the line WebApiConfig.Register(GlobalConfiguration.Configuration); from Global.asax.cs Application_Start.
I have solved by cleaning the deployment directory before copy the new files. Probably there was some old file that try to register the same root multiple times.
I had the same issue and I discovered that in WebApiConfig.cs
and after I added configuration for API version
I have those two lines
config.MapHttpAttributeRoutes(constraintResolver);
config.MapHttpAttributeRoutes();
I removed the second line
the final code is
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof( ApiVersionRouteConstraint )
}
};
config.MapHttpAttributeRoutes(constraintResolver);
config.AddApiVersioning();
// Web API configuration and services
// Web API routes
// config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
For anybody stumbling across this as I did, this error will happen if you rename the Assembly name (project properties). In my case I was renaming a project, and went into the properties to change the assembly name (which VS2013 won't do for you).
Because the assembly name is different, a Clean or Rebuild will not remove the "old" assembly if it is in the \bin folder. You have to delete the assembly from the \bin folder, then rebuild & run.
Probably you have same register more than one.
Try to delete below codes from Global.asax:
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
and write this ones instead of them :
GlobalConfiguration.Configuration.EnsureInitialized();
BundleConfig.RegisterBundles(BundleTable.Bundles);
I am not sure about reason; but it worked for me in my same case.
I was also experiencing a similar problem (not the MS_attributerouteWebApi route in particular, but a different named route). After verifying only one config.MapHttpAttributeRoutes() existed, began realizing that MapHttpAttributeRoutes will register all project assemblies including externally referenced ones. After finding out that I had a referenced assembly that was registering its own routes, I found a way to exclude or "skip over" routes by overriding the DefaultDirectRouteProvider:
/// <summary>
/// Allows for exclusion from attribute routing of controllers based on name
/// </summary>
public class ExcludeByControllerNameRouteProvider : DefaultDirectRouteProvider {
private string _exclude;
/// <summary>
/// Pass in the string value that you want to exclude, matches on "ControllerType.FullName" and "ControllerType.BaseType.FullName"
/// </summary>
/// <param name="exclude"></param>
public ExcludeByControllerNameRouteProvider(string exclude) {
_exclude = exclude;
}
protected override IReadOnlyList<RouteEntry> GetActionDirectRoutes(
HttpActionDescriptor actionDescriptor,
IReadOnlyList<IDirectRouteFactory> factories,
IInlineConstraintResolver constraintResolver)
{
var actionRoutes = new List<RouteEntry>();
var currentController = actionDescriptor.ControllerDescriptor.ControllerType;
if (!currentController.FullName.Contains(_exclude) && !currentController.BaseType.FullName.Contains(_exclude))
{
var result = base.GetActionDirectRoutes(actionDescriptor, factories, constraintResolver);
actionRoutes = new List<RouteEntry>(result);
}
return actionRoutes.AsReadOnly();
}
}
This allows for you to pass a Controller name or Base Type name in to exclude in your WebApiConfig.cs like:
config.MapHttpAttributeRoutes(new ExcludeByControllerNameRouteProvider("Controller.Name"));
Whether or not directly related, hoping this snippet can help!
I was experiencing the same problem. The solution I found was that I needed visual basic support for mono. When I executed "yum install mono-basic" and restarted my computer the error went away.
In my case error was : "A route named 'MS_attributerouteWebApi' is already in the route collection. Route names must be unique.
Parameter name: name"
Code was:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.MapHttpAttributeRoutes(); // this line had issue
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
config.MapHttpAttributeRoutes(constraintResolver);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Solution :
I just removed - config.MapHttpAttributeRoutes();
line from above method and it got resolved.

A route named 'DefaultApi' is already in the route collection

This question may seems duplicate but this is slightly different.
In all other question in SO I had noticed that they have multiple routes registered. but in my case I have just one route.
I am creating asp.net webapi (framework 4.5) and have just one route in RegisterRoutes() method -
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultApi",
url: "rest/{controller}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
Then why is it throwing error?
A route named 'DefaultApi' is already in the route collection. Route names must be unique. Parameter name: name
I had a similar issue with adding a route DefaultApi. Though the exact 'additional details' message in my ArgumentException stack trace was:
A route named 'MS_attributerouteWebApi' is already in the route collection.
Route names must be unique.
I ofcourse made sure I was adding the DefaultApi route only once, but in the end noticed that in Global.asax's Application_Start method I was calling the WebApiConfig.Register(..) twice, though in the following - not immediately obvious - way:
WebApiConfig.Register(GlobalConfiguration.Configuration);
GlobalConfiguration.Configure(WebApiConfig.Register);
Another serious case of 'copypasterites'! I simply removed the WebApiConfig.Register(..) line and that fixed my issue.
(I am using WEB API 2.0/.NET 5)
CAUSE: renaming namespaces without removing associated bin and output files.
SOLUTION: manually delete the bin and obj folders from the output directory. (cleaning the solution is not enough, some problematic residual files remain causing this problem.)
... that was my experience anyway.
Fine, I resolved it based on the reply by user3038092. Instead of adding it in the route collection, I added it in HttpConfiguration
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "rest/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
And it worked.
If you are using MVC4 or MVC5 application.
Then put your Route Configuration in
WebApiConfig.cs and
also check route name should be unique in both files i.e RouteConfig.cs and WebApiConfig.cs
I see that you call the controller but you do not give the controller name like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultApi",
url: "rest/{controller}/{id}",
defaults: new { controller="Home",action="Index",id = UrlParameter.Optional }
);
}
that means you regist HomeContrller for the Index view,

WebApi doesn't get published?

I currently have two controllers. One is MVC and the other is a WebApi controller.
I've published these two with ease on the IIS server with the following settings:
WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
RouteConfig:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "MVCControllerName", action = "MVCControllerName", id = UrlParameter.Optional }
);
Now I've added another WebApi controller, but when published, the webserver says:
No HTTP resource was found that matches the request URI
http://example.com/folder/api/Other?id=45&text=bla
Implementation of the OtherController:
public void Get(int id, string text)
{
// something simply gets commited to the DB
}
Also, something weird is happening when publishing... I've deleted the first WebApi controller from the solution, but for some reason when publishing I can STILL call that WebApi through HTTP GET request! Even though it's gone!
OTOH, it works fine in the debug mode..
What's going on here?
EDIT: It seems the problem is not in my code, but in VS' publishing feature. It has always worked until now. I had to manually copy the files to the server, which isn't the point of so-called "one-click publishing". Other similar SO questions seem to indicate it is a VS bug that is still not fixed in SP2.

Categories

Resources