The api controller in mvc can't be found - asp.net-mvc

I am trying to develop a webapi+angularjs+mvc project .here you can see my apicontroller
public class DefaultController : ApiController
{
testDBEntities a = new testDBEntities();
public IEnumerable<City> Get()
{
return a.Cities;
}
}
Here you can see the webapiconfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
But when i type this : localhost:5411/api/default
i got this error :
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: /api/default

Add the line
GlobalConfiguration.Configure(WebApiConfig.Register) in your Global.asax.cs file
And this will register the webapi routes

Related

How to use string "api" in ASP.NET MVC request URL?

By testing and wasting obscene amount of time I have found out that ASP.NET MVC has a bug which prevents using the string "api" in request URL. I wan to access my method with URL like this
www.mysite.com/api/test
This is not an unexpected wish. In fact it an an obvious Url choice.
Is there a workaround to achieve this?
UPDATE
By request routing definition.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// this executes, checked it in debugger
routes.MapRoute(
name: "Test",
url: "api/test",
defaults: new { controller = "Api", action = "Test" }
);
}
ApiController
public class ApiController : Controller
{
public ActionResult Test()
{
return Content("TEST TEST TEST");
}
{
If you have the WebApi packages installed, you'll find a WebApiConfig.cs class in App_Start. Here's what it looks like:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
So, assuming you don't change the default code in Global.asax.cs, this route gets added to the routing table. Hence, why your /api/whatever route doesn't work.
If you're not using WebApi, I would suggest removing the packages. Otherwise, you can simply change the "root" part of the API route to something else:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
/* changed 'api' to 'restsvc' */
routeTemplate: "restsvc/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

Different Authentication Modes for Asp.Net MVC and Web API on the same site?

I have an ASP.Net MVC4 intranet site that also has a Web API controller.
I have set Authentication = "Windows" in the web.config.
Is it possible to set the Web API only to allow Anonymous?
** Changes I've made to the WebApiConfig file per suggestions below.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Web API routes
config.MapHttpAttributeRoutes();
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
}
}
Sure, inside your WebApiConfig class you need to suppress the default host authentication for the web api only, you can do it as the code below:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.SuppressDefaultHostAuthentication();
}
}
In my project I have achived it with the code below. The project uses Forms Authentication for MVC and Basic Authentication for WebAPI. I use Thinktecture library to achive it.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var authConfig = new AuthenticationConfiguration();
authConfig.AddBasicAuthentication((userName, password) => AuthenticationService.ValidateUser(userName, password));
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
}
}

404 when calling Web API v2

I have a Web Api controller which returns 404 when I call it.
public class ValuesController : ApiController
{
[HttpGet]
public static string Test()
{
return "Hola!";
}
}
Heres the Route Config
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
And here's the Route Debugger info.
I get 404 for below requests
http://localhost:8081/api/values/test
http://localhost:8081/api/values/get
Any ideas why its failing?
Your action is defined as a static method. Actions cannot be static.
[HttpGet]
public static string Test()
{
return "Hola!";
}
Make it an instance method and your code will work.
[HttpGet]
public string Test()
{
return "Hola!";
}

How do I set default Action for Controller?

So I have 2 controller:
[AllowCrossSiteJson]
public class ItemController : ApiController {
[HttpGet]
public LinkedList<Object> FindItem([FromUri]ItemQuery query) {
....
}
}
And
[AllowCrossSiteJson]
public class SubDepController : ApiController
{
[HttpGet]
public LinkedList<Object> FindSubDep(string ID) {
....
}
}
Here is the thing, I try to call both:
http://localhost:43751/api/SubDep
http://localhost:43751/api/Item
And the Item Controller works but the SubDep does not work! Why is that?
Here is my WebApiConfig:
public static void Register(HttpConfiguration config) {
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "withAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
The error I get back is this:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:43751/api/SubDep'.","MessageDetail":"No action was found on the controller 'SubDep' that matches the request."}
BONUS question:
How does ASP.NET MVC know that I try to hit:
http://localhost:43751/api/Item
It automatically go to the FindItem Action? It's like pure MAGIC to me!!
When you try to call FindSubDep action, your query string should be like belwo:
http://localhost:43751/api/SubDep/1
For the bonus question. It gets to the correct action because of the HTTP verb [GET] in your case, when you make a GET request for
http://localhost:43751/api/Item
it will find an action with [HttpGet] attribute on Item controller.

How does routing know where the file is?

My VS project has the following folder and files:
~\Controllers
\AccountController.cs
\HomeController.cs
...
~\Data
\AccountController.cs
...
~\App_Start
\RouteConfig.cs
\WebApiConfig.cs
WebApiConfig.cs contains:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
~\Data\AcccountController.cs contains:
namespace myApp.Data
{
public class AccountController : ApiController
{
[HttpGet]
public string GetUser(int id)
{
//...
}
...
}
}
When I make a http call to /api/Account/GetUser, the call is routed to the GetUser method shown above. What in all of the above or any configuration file tells the server to take the action from this particular file? What if ~/Controllers/AccountController.cs also contain a method of the same name?
It is called convention over configuration.

Resources