What I have so far (that works)
I have an ASP.Net Web API 2 project. Well, at least that's what I remember creating when I set up the project, I am not sure how to confirm that.
I am using Visual Studio 2017, and .Net Framework version 4.6.
In terms of the API side of things, this is all working great. The API controllers are fine, I can get data, post data, etc.
Just a bit of additional information in case it matters, I have added SignalR to the project which has been configured.
As it may be important, here are my various configuration files:
Global.asax.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
What I am trying to do (that doesn't work)
However, I want to add a HTML page so the user can view some information (just static HTML stuff, nothing special). So I have created a standard MVC controller with an action like so (and the Index.cshtml view is in the correct Views folder):
public class NotificationsController : Controller
{
public ActionResult Index()
{
return View();
}
}
The problem is that this action never gets run (I have a breakpoint).
What I have tried to identify the problem
Now I get at this point, it could be loads of different things, so here is what I have tried so far to debug the issue:
When I access the URL in a browser (e.g. http://localhost:59461/Notifications), I get:
localhost is currently unable to handle this request.
HTTP ERROR 500
At first I thought maybe this is a routing issue, however in VS 2017 you can see that a request has failed for this action:
So surely the routing must be working correctly? Unfortunately, clicking the requests only confirms the 500 error and doesn't give any more information about the problem.
The only additional information I can find is in the Windows Event Viewer, in which I get the following error:
Application 'MACHINE/WEBROOT/APPHOST/PROJECTNAME' with physical root 'C:\PATH TO PROJECT FOLDER\' failed to start process with commandline '%LAUNCHER_PATH% %LAUNCHER_ARGS%', ErrorCode = '0x80070002 : 0.
But I have researched that error a lot and am yet to find a suitable solution or explanation for my problem.
I have also tried adding Application_Error but that isn't throwing any exceptions either.
At this point I don't know how to work out the cause of the problem. The only thing I can think of is that I need to configure something specifically to allow Web API projects to work with MVC controllers, but I can't find anything on that either.
What can I do to debug this problem correctly, and find the cause?
Urgh... so I solved the problem...
After stumbling across this post, there is a suggestion to delete the .vs folder in the Visual Studio solution folder. After doing this, and rebuilding the solution, it started working.
No idea what is in that folder that causes this problem exactly though, maybe something got corrupted or some sort of caching conflict, who knows...
Related
I created a WebAPI and all routes and methods work perfectly locally:
WebAPI Local
The problem is when I put it on my web server(The local and web tests are on the same server, so the connection string to the database is correct.).
The standard website and standard methods work normally, but the ones I created don't work(500 Internal Server Error):
WebAPI Server Web
WebAPI Server Web Default Methods
WebApi Server Web Default WebSIte
How can it work perfectly local and not web? since nothing has changed in the code?
The error is as if the url did not exist.
These are the code for the web api method and the RouteConfig file
[Route("WebApi/Users/GetAll")]
[HttpGet]
public IEnumerable<User> GetAll()
{
return _userRep.All;
}
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 }
);
}
UPDATE: Looking in the windows application event logs, I noticed several errors related to localdb. I don't know why it didn't work with LocalDB. As my server is also a domain controller, I had problems getting the SQL server installed but I managed with this tutorial: http://lexisnexis.custhelp.com/app/answers/answer_view/a_id/1089877/~/installing-sql-on -a-domain-controller
After that I pointed to the SQLServe instance instead of LocalDB and it worked.
you need to provide more information about your controller
place this on the controller if not present
[Route("api/[controller]")]
Summary
A Kentico 8.2 website fo which I have recently implemented a Web API service isn't registering routes on first deployment and all calls return 404. Further redeployments usually fix the issue, but I would like to fix it permanently before it is released to PROD.
What is preventing the first deployment from registering the route properly?
Background
We have a Kentico v8.2.12 website that uses Web Forms using .NET Framework v4. I have registered a Web API Controller, but it appears on the first release the route isn't registered and any calls to the service returns "404 (Not Found)".
When I first deployed to the DEV environment the Web API route wasn't registered, but upon deploying another build it magically worked. One or two other releases into the DEV environment caused similar issues, but in these instances re-deploying the same build worked.
The same issue has now occurred when released to UAT, however as the deployments are carried out by another team it will be more time-consuming to re-deploy builds and looks unprofessional. I am also wary of this occurring in PROD---which may cause the live website to be down further than necessary.
Web API Implementation
The Web API Controller is inside the CMS Website project and not a separate library.
Global.asax.cs
The Global.asax.cs file's Application_Start() method registers the route and looks similar to the below:
protected void Application_Start()
{
// Scripts Bundling here, which havs been removed for brevity
BundleTable.EnableOptimizations = false;
// Registering the API
RouteTable.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {id = RouteParameter.Optional}
);
}
MyController.cs
My Controller looks similar to the below stored under the CMS website: CMSApp/ApiControllers/MyController.cs
[assembly: RegisterApiController(typeof(CMSApp.ApiControllers.MyController))]
namespace CMSApp.ApiControllers
{
public class MyController : ApiController
{
Channel Channel = new Channel();
[HttpPost]
public int Create()
{
Response objResponse = Channel.Instance.DoSomething();
HandleResponse(objResponse);
return objResponse.SessionHandle;
}
}
}
In the webbrowser, accessing /api/my/create returns a 404 (Not Found), but I expect it to tell me it's a POST method.
Lib versions [Edit, I have since updated the libs but issue still prevails]
Microsoft.AspNet.WebApi : v4.0.30506
Microsoft.AspNet.WebApi.Client : v4.0.30506
Microsoft.AspNet.WebApi.Core : v4.0.30506
Microsoft.AspNet.WebApi.WebHost : v4.0.30506
Question?
Why do the first deployments into an environment not work, but most further deployments work as I expect them to?
The issue was due to ASP.NET caching.
Once "MS-ApiControllerTypeCache.xml" was removed under "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files" and IIS was restarted, the controller was picked up.
I am doing an MVC5 Web API Application. I am doing an simple example.
Create an Web Asp.Net web Application.
Select Empty and API.
Then I add a Api2 Controller called Home, and add a Simple Method called Get()
Method Get() looks like this.
public string Get()
{
return "Hello World";
}
I run the application and complete the URL.
http://localhost:56464/Home/Get
Got an error
Error HTTP 404.0 - Not Found
I test changing WebApiConfig adding
{action}
but I get the same error.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
When I start the Application http://localhost:56464/, I got this error
Error HTTP 403.14 - Forbidden
I always run the Application from Visual Studio 2013. I did not publish it it IIS
What is missing?
There are a few issues.
First the web api route template is
api/{controller}/{action}/{id}
Note the api prefix.
So that would mean that you have to browse to
http://localhost:56464/api/Home/Get
http://localhost:56464/ wont work because the route has the api prefix. So the forbidden error is default for what ever is hosting at that address.
To be able to use the URL you want in the question you would need to change the route template to match your desired template.
So it's my first time setting up an netcore MVC based application. I've used MVC 4 in the past on plain old asp.net.
So i'm having issues with my routing. My application is an single page application (spa) that is accessible from the home controller on the index action. I can access this controller method fine, and my defaults are set so that this is navigated to at route: /.
I also have a second controller for authentication called AccountController. This controller's methods take and return JSON, rather then views. I can also access the methods on this controller from my application.
The issue i'm having lies in my next controller, which is the start of my API.
As such, i've put it in a folder called api inside my controllers folder. However, no matter what i try, i cannot seem to get the methods on the controller accessible. I have also tried moving it out of the api folder and just having in the route of the controllers folder.
The routing deffinition
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller=Core}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I've tried adding and removing the api definition, removing the api part, and adding a template for actions aswel, all to no effect.
The troublesome controller
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I've tried adding [Route(~routing here~)] annotations to this controller and its methods with no success either.
Folder structure
I should also mention that i've tried plenty of URL's to access this controller on:
/api/Core/
/Core/
/api/Core/Get
I've been wracking my brain for the best part of a day trying to get this sorted and i know i'm missing something obvious, i just can't for the life of me work out what it is.
Edit:
I've added a cut-down sample of my project to github at: https://github.com/lexwebb/aspnet-test if anyone would like a complete example
Edit 2
It appears that my example works, i'm going to add things in to see what breaks it
AFAIK, default route requires the {action} using as well.
Instead of "api" default routing, you may to use the following configuration for such type of controllers (RESTFul controller):
[Route("api/[controller]")]
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I found this Routing is ASP.NET Core article useful in the past.
So as it turns out, i had made a mistake in a totally unrelated place. I had renamed my project half way through the beginning stage of development, after i had build scripts in place. This led to the the wrong dll being referenced on the server when the code was ran, a version that had all of my routing EXCEPT the new one, of course.
With the help of several online tutorials, like this one, I am still struggling to add a Web API service to an existing Asp site, that is not MVC.
I added to the project a new item of type Web API Controller Class(v2.1), named it something like AbcController.cs, and VS2015 asked me to put it in the App_Code directory. The default code has handlers for Get, Put etc. Sounded to me like I am on the right track.
I added a default route in Global.asax.cs like in the tutorial:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
This got built after adding a reference to System.Web.Http.Webhost which was not mentioned in the tutorial. Sounded like I was still on the right track.
However, it doesn't work. I run the site in debug and this gives me a 404 Not Found:
http://localhost:54905/api/abc
I tried to run this on the production server with IIS7, of course as a second test web site to not interfere with the version that is in production. However, I ran into the error that the Microsoft.Web.Infrastructure dll could not be found. To fix this, I should install MVC packages, which I don't like for just an experiment.
My questions are:
do I get it right that the URL is in lower case, i.e., not .../api/Abc ?
does this kind of routing work in the debugger?
am I essentially turning the web site into an MVC web site?
is this really the simplest way to add a "REST" service to an existing web site? I only need to implement the POST, read and return some JSON data, and do not need arguments in the URL