API Ignored, Home View Called - c#

Was coaching a colleague on Web API. Just trying to run the default Web API template out of the Visual Studio box, as it were...not even doing anything fancy. A default (Get) call to my API (api/{controller}/{id}) keeps returning the MVC home view instead of the contents of the Get method in my API controller.
namespace WebAPI.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
...
namespace WebAPI
{
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 }
);
}
}
}
namespace WebAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
I've looked far and wide across the 'Net but can't find anything address my specific problem.
I expected the default value1, value2, etc. Instead, the MVC home view keeps returning instead.

Related

How to use dependency injection in an ASP.NET Web API 2 controller using Unity?

In Visual Studio 2019, I created an ASP.NET Web API project. I created a Web API 2 controller. I followed this link 1 and link 2 to implement dependency injection using Unity.
I have shared the code according to link 1 but it is not working. I get an error in method GetService(Type serviceType) of UnityResolver (which I copied from first link).
Error is:
Exception thrown: 'Unity.ResolutionFailedException' in Unity.Container.dll
I checked this using breakpoints. It is returning null although container is not null.
I have been searching this so long. I don't understand where it is wrong or I did something wrong.
I am new to .NET Framework and also to programming. Any help or advice appreciated.
public object GetService(Type serviceType)
{
try
{
return container.Resolve<Type>();
//return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
MyAPIController.cs
public class MyAPIController : ApiController
{
private IAgent agent;
public MyAPIController (IAgent _agent)
{
this.agent= _agent;
}
[HttpPost]
[Route("AgentService")]
public string GetAgentServices([FromBody] InputData inputData)
{
return "nothing";
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var container = new UnityContainer();
container.RegisterType<IAgent, Agent>();
config.DependencyResolver = new UnityResolver(container);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}

Default controller action for Web API in Asp.Net MVC

My Web API on an Asp.Net MVC web app is returning 404 error when receiving requests that don't specify any controller.
The calls that are returning 404 error are:
https://myWebApp/api/
The goal would be to handle these type of requests without returning error and return something like "true" or "new EmptyResult()".
Current routing for the Web API includes the following in WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new IdentityBasicAuthenticationAttribute());
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
While I have routes explicitly defined for each API controller:
[IdentityBasicAuthentication]
[Authorize]
public class myApi1Controller : ApiController
{
[HttpGet]
[Route("api/myApi1")]
public string Get(string id) { ... }
}
I have tried to route these calls to a default API or MVC controller without success.
My current RouteConfig for the MVC app is:
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 },
namespaces: new[] { "myWebApp.Controllers" }
);
}
}
The order in which these are called is:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Create a controller to handle that route so it does not fail with not found
Like
[RoutePrefix("api")]
public class MyEmptyController : ApiController {
//GET api
[HttpGet]
[Route("")]
public IHttpActionResult Get() {
return StatusCode(HttpStatusCode.NoContent); //204
}
}
Using attribute routing as it is already enabled via config.MapHttpAttributeRoutes(); in WebApiConfig
Your route config is different from your WebApi config and I don't know the order that you are calling them.
in your RouteConfig:
url: "{controller}/{action}/{id}",
which means: http://localhost:PORTNUMBER/myApi1/ACTION
in your WebApiConfig
routeTemplate: "api/{controller}/{id}",
(method and id are optionals)
which means: http://localhost:PORTNUMBER/api/myApi1/?id=value
change your WebApiConfig, and you even will be able to avoid using the Route tag in your controller :
[IdentityBasicAuthentication]
[Authorize]
public class myApi1Controller : ApiController
{
[HttpGet]
public string Get(string id) {
return "works!";
}
}
Edit:
Keep every thing the same, Invoke your default GET method from:
http://localhost:PORTNUMBER/api/myApi1

web api in MVC no longer working

I am using VS 2017 community. I have been building web api s for years. But something must have changed as I cannot get the simplest example to work.
I have a simple controller in the controller folder
public class TestApi : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
I have the necessary code in application start:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
But when I try and test the web api with a get like:
http://localhost:54014/api/testapi
I always get an xml message
Error
Message
No HTTP resource was found that matches the request URI
'http://localhost:54014/api/testapi'.
/Message
MessageDetail
No type was found that matches the controller named 'testapi'.
/MessageDetail
/Error
Here is the WebApiConfig.cs
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 }
);
}
}
I am a couple of hours into head scratching on this. As I say I have built many MS web api implementations and this one has me baffled.
You should add Controller suffix to your class name.
public class TestApiController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
When the app starts, the asp.net mvc frameworks looks for classes (which are inherited from ApiController or Controller) with this suffix and register them when building the route table. When a request comes to your app, the framework again look into the route table and direct the request to the corresponding controller and action method.
Make this change, rebuild your project and try again.
In addition to the already provided answer (which is correct by the way) you can also consider using attribute routing over convention-based routing, where in this case it would not matter what the name of the controller is.
You already have it enabled Based on the WebApiConfig.cs and
config.MapHttpAttributeRoutes();
So now it is just a matter of putting the attributes where needed
[RoutePrefix("api/testapi")]
public class TestApi : ApiController {
[HttpGet]
[Route("")] //Matches GET api/testapi
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
}
Reference: Attribute Routing in ASP.NET Web API 2

.NET Web api 2 stops working after sometime in IIS

I have two web API project DLLs in one solution.
Structure of my Project Solution:
In my solution, the projects are located as follows:
1) Base Solution
2) Base Web API
3) Module Web API
Hence, my solution is something like a BASE solution which contains many MODULES. Each Modules can contain its own Web APIs. Also, my Base Solution contains its own Web API
This is our structure.
My Problem:
It is working fine in my local run solution. When I host it to the IIS, it is working for few hours and then it stops working by throwing the error message "Error 404 found". When I try to access through URL directly which is something like "http://127.0.0.1:51/Products/Get", not working.
Visual Studio version:
Visual Studio Professional - 2015
IIS Version:
IIS - 7.5.7600
My approach:
I have a simple project which simulates this scenario. It has the same problem with my original project.
Web API For Base Module:
WepApiConfig under App_Start:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// 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 }
);
}
}
Base API Controller:
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
}
WebApiConfig.cs For Module Web API:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// 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: "DefaultModuleApi",
routeTemplate: "api/module/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Module API Controller:
public class ModulesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
}
NOTE from the above code:
The difference between the two APIConfig files is :
For Module Code:
routeTemplate: "api/module/{controller}/{action}/{id}"
For Base Code:
routeTemplate: "api/{controller}/{action}/{id}"
Global.asax:
namespace BaseSln
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//GlobalConfiguration.Configure(WebApiConfig.Register);
var typesWithMyAttribute =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetLoadableTypes().Where(t1 => t1.Name == "WebApiConfig"
&& t1.GetMethod("Register") != null
&& t1.GetMethod("Register").IsStatic)
select new { Type = t, MethodInfo = t.GetMethod("Register") };
//register all the Routes
foreach (var type in typesWithMyAttribute)
{
var mi = type.MethodInfo;
Action<HttpConfiguration> action = null;
try
{
action = Delegate.CreateDelegate(typeof(Action<HttpConfiguration>), mi) as Action<HttpConfiguration>;
}
catch
{
//ignore the errors for now... should be handled somewhere else or logged.
}
if (action != null) GlobalConfiguration.Configure(action);
}
}
}
}
What I tried with the above project:
After hosting in IIS, I tried to access the path which is something like this:
For Base API:
http://localhost:51600/api/Values/Get
Returns:
value1
value2
For Module API
http://localhost:51600/api/Modules/Get
Returns:
value1
value2
My problem:
After sometime, when I try to access the same link, I am unable to get that. It says
status 404. Not Found
I have been working on this issue for 3 days, and I couldn't resolve the problem.
I have searched many articles in stackoverflow, but no luck.
Kindly help me to get rid off from this.
Thanks.
Can you check the GlobalConfiguration.Configuration.Routes in the Base Solution if you have all the routes for both the Base Web API and the Module Web API?

Web API calling Error ASP.Net MVC

I am developing a web api but it can not hit it. Error shows 404 not Found.
Web Api
using Atea.Azure.ApiMangement.Business;
using System.Web.Http;
namespace Azure_API_Delegation_Portal.Controllers
{
[RoutePrefix("api/apim")]
public class ApimController : ApiController
{
private readonly ISubscriptionService _subscriptionService;
[HttpGet]
[Route("{string:productId}")]
public bool GetProductSubscribe(string productId)
{
return _subscriptionService.IsSubscribed(productId);
}
}
}
How I call an API https://localhost:44300/api/apim/ldkjfk232
Web API Route
using System.Web.Http;
namespace Azure_API_Delegation_Portal
{
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 }
);
}
}
}
Image
I am missing this line of code in Application_Start() function in "Global.asax" file.
GlobalConfiguration.Configure(WebApiConfig.Register);
Fix your route template. It is string by default so no need for the string constraint
//GET api/apim/ldkjfk232"
[HttpGet]
[Route("{productId}")]
public bool GetProductSubscribe(string productId)
Also note that the constraint goes after the placeholder name like this example
[Route("{paramaterName:int}")]
Read more about attribute routing here : Attribute Routing in ASP.NET Web API 2
It will show you how to properly configure your web api.

Categories