url of webapi, how to configure in mvc - asp.net-mvc-3

I Have a url to a webapi, like this:
http://Dynamicweb8724.nl/webapi/NavToDW/?process="
and in the mvc project I have this files:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultApi",
url: "DefaultApi/{action}/{id}",
defaults: new { controller = "Guestbook", action = "Index", id = UrlParameter.Optional, PageID = 1067 }
);
}
}
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "webapi/NavToDW",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
and the Global.asax file:
public class Global : System.Web.HttpApplication
{
public void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.RazorViewEngine());
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.WebFormViewEngine());
// Fires when the application is started
Dynamicweb.Frontend.GlobalAsaxHandler.Application_Start(sender, e);
GlobalConfiguration.Configuration.EnsureInitialized();
}
public void Session_Start(object sender, EventArgs e)
{
// Fires when the session is started
Dynamicweb.Frontend.GlobalAsaxHandler.Session_Start(sender, e);
}
public void Application_BeginRequest(object sender, EventArgs e)
{
// Fires at the beginning of each request
//GlobalAsax.Application_BeginRequest(sender, e);
}
public void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Fires upon attempting to authenticate the use
Dynamicweb.Frontend.GlobalAsaxHandler.Application_AuthenticateRequest(sender, e);
}
public void Application_Error(object sender, EventArgs e)
{
// Fires when an error occurs
Dynamicweb.Frontend.GlobalAsaxHandler.Application_Error(sender, e);
}
public void Session_End(object sender, EventArgs e)
{
// Fires when the session ends
Dynamicweb.Frontend.GlobalAsaxHandler.Session_End(sender, e);
}
public void Application_End(object sender, EventArgs e)
{
// Fires when the application ends
Dynamicweb.Frontend.GlobalAsaxHandler.Application_End(sender, e);
}
public void Application_OnPreRequestHandlerExecute(object sender, EventArgs e)
{
Dynamicweb.Frontend.GlobalAsaxHandler.Application_OnPreRequestHandlerExecute(sender, e);
}
}
So I can connect. But I can't go to the specific link, like this:
http://dynamicweb8724.nl/webapi/NavToDW/?process=
the outcome is this:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
bij System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() bij System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) bij System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>
Controller:
public class GuestbookApiControllerController : ApiController
{
// GET: GuestbookApiController
public IEnumerable<GuestbookEntry> Get()
{
return ItemManager.Storage.GetByParentPageId<GuestbookEntry>(1067);
}
}
So what I have to change?
But If I put a breakpoint on this method:
public void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.RazorViewEngine());
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.WebFormViewEngine());
// Fires when the application is started
//GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
GlobalAsaxHandler.Application_Start(sender, e);
GlobalConfiguration.Configuration.EnsureInitialized();
}
it doesnt hit.

Your route configuration for the WebApi needs to be fixed. You placed the route template of what you wanted into the name of the route rather than the template itself.
Given the intended Url...
http://Dynamicweb8724.nl/webapi/NavToDW/?process="
There are a few changes you need to make.
First your api controller needs to be able to accept the parameter process and I would also rename the controller to follow convention.
public class GuestbookApiController : ApiController
{
// GET: GuestbookApi
public IEnumerable<GuestbookEntry> Get(int process)
{
return ItemManager.Storage.GetByParentPageId<GuestbookEntry>(process);
}
}
And finally you need to properly map the intended URL to the controller action.
public class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
// Convention-based routing.
//This will map to the intended controller
config.Routes.MapHttpRoute(
name: "GuestBookApiRoute",
routeTemplate: "webapi/NavToDW",
defaults: new { controller = "GuestbookApi" }
);
//This is the default api route
config.Routes.MapHttpRoute(
name: "DefaultWebApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The above shows how to do convention based routing. You can also achieve the same with attribute routing. You can take some time and read up on the topic if you want to do attribute routing

Related

No HTTP resource was found that matches the request URI in MVC application

WebApiConfig.cs
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 }
);
}
}
Global.aspx
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Api Controller
[RoutePrefix("api/buyinsurance")]
public class buyinsuranceapi : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Calling API Url
Error image
I have added API controller in the existing MVC application that time I have faced an issue.
please if anyone has an idea give me suggestion

WebApi controller isn't found

I have an example controller in my WebApi-project:
public class MilestonesController : ApiController
{
// GET api/milestones
public IEnumerable<string> Get()
{
return new string[] { "M#1", "M#2" };
}
// GET api/milestones/5
public string Get(int id)
{
return "M with {id}";
}
// POST api/milestones
public void Post([FromBody]string value)
{
}
// PUT api/milestones/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/milestones/5
public void Delete(int id)
{
}
}
If I try to navigate to it:
http://localhost:59493/api/milestones
I always get the error:
No HTTP resource was found that matches the request URI 'http://localhost:59493/api/milestones'.
No type was found that matches the controller named 'milestones'.
Thank you in advance!
Edit:
my WebApiConfig:
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 }
);
}
}
Global.asax:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Possible Solution:
I have deleted my project and I've created a new one (WebAPi project) and now it works. The WebApiConfig etc was the same, so I don't really know what was wrong with my first try
you're missing the 'api' section of the url from your route. Try something more like;
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Take a look at where you created that controller. Maybe it is not in the Controllers folder, different namespace or that controller class is nested into another class

MVC Override OnException Error: No suitable method found to override

I'm trying to override OnException in Global.asax to handle error and writing log. I'm not sure which part is wrong, I keep on getting the error "MyApp.MvcApplication.OnException(System.Web.Mvc.ExceptionContext)': no suitable method found to override" whenever I rebuild my solution.
this is the code I have in Application_Start()
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
And this is the code I have in OnException()
protected override void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
if (!string.IsNullOrEmpty(ex.Message) ||
!string.IsNullOrEmpty(ex.Source.ToString()) ||
!string.IsNullOrEmpty(ex.StackTrace))
{
WriteLog(ex.Message.ToString(), ex.StackTrace.ToString(), ex.Source.ToString(), "0");
context.Result = new ViewResult
{
ViewName = String.Format("~/ErrorPage/ErrorPage?message={0}&stack={1}&source={2}", HttpUtility.UrlEncode(ex.Message), HttpUtility.UrlEncode(ex.StackTrace), HttpUtility.UrlEncode(ex.Source))
};
}
context.ExceptionHandled = true;
}
The WriteLog() function is tested working in other application, I don't think there's any problem in it and I even tried:
protected override void OnException(ExceptionContext context) {
Exception ex = context.Exception;
context.Result = new ViewResult
{
ViewName = "~/Shared/Error.cshtml";
};
context.ExceptionHandled = true;
}
But nothing work. The error just remain there.
How could such problem occur and how do I fix it? I read many tutorial about this, I don't think I'm spelling OnException() wrongly.
Please help. Thanks
There isn't any OnException inside Global.asax
You have two ways:
Create your own HandleErrorAttribute and register in FilterConfig.cs
public class HandleExceptionsAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
(...)
}
}
FilterConfig.cs:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionsAttribute());
(...)
}
Or, if you have a BaseController where all controllers are inherited from, override the OnException method.
PS: I would go for the filter one.
There is no method OnException in the global asax, that method belongs to the controllers.to handle errors in the global asax use the method Application_Error(object sender, EventArgs e)

ASP.NET Web API resource not found error

I have added a Api Controller in my asp.net mvc5 web project, along with other controllers...i am contstantly getting resource not found error. please point out mistakes i might be making...
following is my Register method for WebApi routes
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
here is the Global.asax.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//GlobalConfiguration.Configure(WebApiConfig.Register);
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
here is my Api controller class
public class SearchController : ApiController
{
public IEnumerable<string> GetSearch()
{
return new string[] { "value1", "value2" };
}
}
"http://sukhdev.com/api/search" is the url scheme i use to call web api, but it persistenly "The resource cannot be found."
Why did you commented //GlobalConfiguration.Configure(WebApiConfig.Register);
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Getting "The resource cannot be found." error when using Ninject

I'm working on an ASP.NET MVC 3.0 application, using Ninject as my dependency injection framework.
So I've inherited my controller from NinjectHttpApplication like so:
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
}
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new NinjectDependencyResolver(Kernel));
}
protected override Ninject.IKernel CreateKernel()
{
return new StandardKernel(new QueriesModule());
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" },
new string[] { typeof(HomeController).Namespace }
);
}
}
But whenever I run the application and try to browse to any of my controllers, I get the 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: /Home/Index
What's causing this and how do I fix it?
Turns out this was occurring because the NinjectHttpApplication class from which I'm inheriting is calling the OnApplicationStarted() method at startup. So the solution is to remove the Application_Start() method and move all that code into OnApplicationStarted().

Resources