404 trying to use web api endpoint - asp.net-mvc-4

I'm trying to add a web api controller to my MVC project. It's an MVC 3 project that I've upgraded to MVC4. I'm trying to get the "test" simple api controller to work, and currently getting a 404. Here's what I've done:
I've added all the required packages.
I've added my webapi config to my Global Application_Start():
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration); // Web API
This then calls my static Register method:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I have a ApiController defined in my web app:
public class SitechangesController : ApiController
{
/// GET api/default1
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
And finally, when I build it all and browse to my site on localhost http://localhost/api/Sitechanges , I get a 404.
If I do a file/new project and create a web api project from scratch, I don't have these problems. Can anyone help?
Thanks
Matt

It seems adding the web api config before the "normal" routes fixes it!
WebApiConfig.Register(GlobalConfiguration.Configuration); // Moved to the top
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

Your controller must end in ...Controller.cs.
For example:
Test.cs and TestControllerV2.cs will return 404.
TestController.cs and TestV2Controller.cs will return 200.
I see yours does, but I came across your post when searching for why a 404 was returned.

Related

getting 404 for get api controller result after changing startup to OWIN

I start with Empty asp.net web api application with all default settings for VS 2017. I added one controller method with httpGet and result is fine.
Now I installed Microsoft.Owin.Host.SystemWeb and added a OWIN Startupclass.
[assembly: OwinStartup(typeof(WebApp1.Startup))]
namespace WebApp1
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
After that I comment out global.asax code as I believe I don't need it,
protected void Application_Start()
{
//GlobalConfiguration.Configure(WebApiConfig.Register);
}
Removing as well below code for Web API routes
//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 }
// );
// }
//}
Now I'm getting 404 error while accessing the API, my OWIN startup code also calling. Whats wrong here? please suggest!.
You have to add the following line of code at the end of your OWIN Configuration method:
app.UseWebApi(config);
Note: this method is located in:
using Owin; //Assembly System.Web.Http.Owin

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory Visual Studio Debugging MVC 4 solution

I am trying to debug a visual studio MVC 4 solution with the following route config content.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(name: "RegistrationForm", url: "{RecruitmentRegistration}/{Registration}/{id}",
defaults: new { controller = "RecruitmentRegistration", action = "Registration", id = UrlParameter.Optional });
}
But while trying to access the controller Action method, I am facing the below listed error.
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
But when I try with the default Index action method it is working fine with the Index view getting loaded.
Below are the Controller Class contents
public class RecruitmentRegistrationController : Controller
{
//
// GET: /RecruitmentRegistration/
public ActionResult Index()
{
return View("Index");
}
public ActionResult Registration()
{
return View("RegistrationForm");
}
}
When I checked for solutions, I could find that most of the solutions are related to IIS related setting changes.But here I have not used IIS site setup and I am directly browsing from the VS2012.
Please advise.

Unable to call WebApi 2 method

I've added a webapi 2 controller to my project, inside api > LoginAPi as shown here:
Inside LoginApi I have the following:
[RoutePrefix("api/LoginApi")]
public class LoginApi : ApiController
{
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
}
Inside my global.asax file I have:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
Inside App_Start I have the following:
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 }
);
}
I then put a break point inside the Get method within LoginAPI and run the project and type the following into the URL:
http://localhost:37495/api/LoginApi/4
But I get :
No HTTP resource was found that matches the request URI 'http://localhost:37495/api/LoginApi/4'.
So I thought OK let me specify the method name as so
http://localhost:37495/api/LoginApi/Get/4
This returns:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Now I've been looking at this for a while so maybe I've missed something obvious, but if someone can please tell me what I'm doing wrong I'd very much appreciate it.
The routeTemplate you have set up would work for convention-based routing except for the fact that Web API adds the string "Controller" when searching for the controller class (as per this article). You therefore need to rename your controller class LoginApiController in order for the convention-based routing to work.
For attribute-based routing, the addition of the RoutePrefix attribute should be combined with a Route attribute on your action. Try adding the following to your Get method in your controller:
[HttpGet]
[Route("{id}")]
And then navigate to http://localhost:37495/api/LoginApi/4.

Visual Studio MVC4 Auto Url Routing for All Url's

Hello everyone I am working with VS13 MVC4 in localhost, for url routing I want VS will work for all url's automatically as www.sitename.com/about-us but now it is getting underscore (_) not dash (-) how to make a change and get hyphen(-) before every new word in url
Here is the answer I also add it to my question for everyone can see:
public class HyphenatedRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
return base.GetHttpHandler(requestContext);
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(
new Route("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "Default", action = "Index", id = "" }),
new HyphenatedRouteHandler())
);
}
}
Thanks everyone.
If you want pretty url in asp.net mvc then you should go by registering new route for your controller.
from the application directory open RouteConfig.cs in the App_Start directory.
And in the RegisterRoutes method of RouteConfig class register a new route like this-
routes.MapRoute(
name: "AboutUs",
url: "sitename/about-us",
defaults: new { controller = "About_Us", action = "Index" }
);
The _ will prob be automatically converted to a - in the routing. The other way is to set up the routing yourself

Add Web Api controllers to an existing ASP.NET 4 web application

Following the steps from this question How to add Web API to an existing ASP.NET MVC 4 Web Application project? , I have added web api support to my application.
In my original scenario I have the following web mvc controller:
public class FranchiseController : Controller
{
public ActionResult List()
{
return View();
}
[DataContext]
public ActionResult GetAllFranchises()
{
var franchiseInfoViewModelList = new List<FranchiseInfoViewModel>();
var franchiseInfoList = _franchiseService.GetAll();
foreach (var franchiseInfo in franchiseInfoList)
{
franchiseInfoViewModelList.Add(new FranchiseInfoViewModel(franchiseInfo, p => p.IsImportant));
}
var jsonNetResult = new JsonNetResult
{
Formatting = Formatting.Indented,
Data = franchiseInfoViewModelList
};
return jsonNetResult;
}
}
When the user navigates to the List view, I am calling
$.getJSON("/franchise/GetAllFranchises")
.done(function (data) {
});
to go to the GetAllFranchises action method and return the json data. So far so good.
I have created the following web api controller:
public class FranchiseController : ApiController
{
public IEnumerable<FranchiseInfoViewModel> GetAllFranchises()
{
var allFranchises = new List<FranchiseInfoViewModel>();
var franchiseInfoList = _franchiseService.GetAll();
foreach (var franchiseInfo in franchiseInfoList)
{
allFranchises.Add(new FranchiseInfoViewModel(franchiseInfo, p => p.IsImportant));
}
return allFranchises;
}
}
and I am trying to get to its action method like this:
$.getJSON("api/franchise")
.done(function (data) {
});
I am getting 404 error and the app is trying to reach the following url:
/Franchise/api/franchise
instead of api/franchise.
Global Asax:
protected void Application_Start()
{
Log.StartSession();
ElmahExtension.SetCurrentApplication(this);
ViewEngines.Engines.Add(new OmegaViewEngine());
AreaRegistration.RegisterAllAreas();
SerializerConfig.Register(GlobalConfiguration.Configuration);
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
Bootstrapper.Initialise();
FluentValidationModelValidatorProvider.Configure();
}
Default route:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
In my Controllers folder I have my web mvc controller:
Controller\FranchiseController
and I have made a new folder WebAPI to hold my web api controller
Controller\WebAPI\FranchiseController
What am I doing wrong ? Thanks!
I'm not sure if it's the right move to name "FranchiseController" both to the MVC Internet Application Controller and to the MVC Web API Controller (totally different things). After renaming one of them I think you should put the Web Api Controller in the root of the directory (Controller).