ASP.NET WebAPI methods working only local but not on WebServer - c#

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]")]

Related

Simple controller routing doesn't work in IIS for asp.net site hosted in IIS

Trying to host locally a rest service in IIS. Everything works fine in IIS Express but as soon as I try to host locally in IIS the routing doesn't work.
It's compiled to x86 and is hosted inside of an app pool that allows for 32 bit processes.
I have the site mapped to the binary output folder from my build msbuild /p:Configuration=Release /p:ProcessorArchitecture=x86 -r:False
I have Anonymous Authentication enabled
Binding is type http to port 8000
I have enabled directory browsing and see the below at http://localhost:8000/
However whenever I try to navigate to http://localhost:8000/api/HeartBeat I get a 404 - Not Found.
My WebApiConfig class which sets a default route.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Here is the controller
public class HeartBeatController : ApiController
{
// GET: api/HearBeat/5
public HttpResponseMessage Get()
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
If I run this in IIS Express and navigate to that same url I get a 200. Also I've tried to examine the URL in powershell using Get-WebUrl and it shows a ProtocolError but I have no clue what or why. And IIS Manager doesn't seem to complain about anything.
PS C:\Windows\system32> Get-WebURL -PSPath "IIS:\Sites\Test" | Format-list
Status : ProtocolError
ResponseUri : http://localhost:8000/
Description : Forbidden
A couple of things were amiss.
Publishing via Visual Studio is quite different than the build output that was created via the build command above.
I was missing under Windows features/IIS/Application Development Features
Finally was still getting a security error which required adding an ACL rule to the directory

Unable to use MVC Controller with ASP.Net Web API 2

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...

MVC Web Api error 403.14

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.

WebApi Route is getting moved to base URL after publish

I have a very simple route in an application that works fine from Visual Studio, but when I run through the publish process and deploy it to an IIS 8.5 server it changes the route and resolves from the base URL. I believe it has something to do with the route mappings, but I'm not sure why it's being interpreted differently.
When I launch in Visual Studio and visit http://localhost/test - it works great. If I visit http://localhost - I receive a 403 like I'd expect.
After I publish to IIS, the inverse happens. http://servername/test resolves to a 404, and http://servername now resolves my test page.
Any help would be appreciated in understanding this behavior. Visual Studio version is 2015, and IIS is version 8.5. WebAPI version is 5.2.3.
Controller:
[Route("test")]
public class WebApiController : ApiController
{
private static readonly ILogger Logger = Log.Logger.ForContext<WebApiController>();
[Route("")]
public string Get()
{
return "Services started. Current response time is: " + DateTime.Now.ToString("h:mm:ss tt");
}
}
Route registration:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "",
defaults: new { }
);
}

How to host WCF Data Service in ASP.Net MVC3 app

I have written several WCF data services and find them quite useful. However, I have found routing to be quite a pain. I have seen conversations that indicate that you can host a data service in an ASP.Net MVC app (I have always used ASP.Net web sites). However, I do not seem to be able to find any examples of how to achieve this. Does anybody have any references I could check-out or advice?
The question was posted some time ago but I assume there are still people interested in using WCF Data Services in ASP.NET MVC projects.
Assuming that you have in your project a service called: 'DataSourceService.svc' you can use this service in an MVC project by configuring the routing in 'RouteConfig.cs' as follows:
using System.Data.Services;
using System.ServiceModel.Activation;
using System.Web.Mvc;
using System.Web.Routing;
namespace <YourNamespace>
{
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 },
// the controller should NOT contain "DataSourceService"
constraints: new { controller = "^((?!(DataSourceService)).)*$" }
);
routes.Add(new ServiceRoute("DataSourceService", new DataServiceHostFactory(), typeof(DataSourceService)));
}
}
}
Make sure that you have in Web.config the following configuration:
<configuration>
...
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
...
</configuration>
Now you can check that everything works fine by running your project in the browser and using the following url:
http://localhost:port_number/DataSourceService/$metadata
... which should return your metadata.
The WCF web api may do what you're looking for. Here's their getting started page. You host the service inside of the MVC app, and even hook into into the same routing that MVC uses.

Categories