The resource cannot be found when invoke ApiController method - c#

When i try to invoke api controller the getting 404. But when i try to invoke Controller method its working fine. Please help and let me know if any information is required.
TPServicesAPIController.cs:-
using AgentVartualOffice.Models.LogIn;
using System.Web.Mvc;
using AgentVartualOffice.Models;
using Newtonsoft.Json;
using System.Text;
namespace AgentVartualOffice.Controllers.TPServices
{
public class TPServicesAPIController : ApiController
{
public string Myauth()
{
return "True";
}
}
}
Global.asax.cs:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;
namespace AgentVartualOffice
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalFilters.Filters.Add(new HandleErrorAttribute());
}
}
}
Invoke url:
http://localhost:61868/TPServicesAPI/Myauth

Chances are your are calling the wrong URL.
The default Web API convention-based routes are usually prefixed with api
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}", //<<--- default web API route template
defaults: new { id = RouteParameter.Optional }
);
}
}
and also do not use action names unless the route template has been changed.
routeTemplate: "api/{controller}/{action}/{id}"
So I suggest you check your API config and update the URL being called accordingly.
For example, by calling: api/TPServicesAPI/Myaut

Related

API Controller added to ASP.NET MVC web application doesn't seem to work

I have an ASP.NET MVC web application that I'm trying to add an API Controller to so that I can make front-end AJAX calls with jQuery.
I have seen several posts on stack overflow about how to add an API controller successfully to an MVC project and although I followed the instructions and have tried to avoid the common issues (I have added the required API dependencies and made sure that my API routes are being initialized before the MVC routes in my global.asax.cs)
My API Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace mywebsite.net.Controllers
{
public class WebAPIController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
My WebApi.config:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace mywebsite.net
{
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 }
);
}
}
}
My Global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
namespace mywebsite.net
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
When I try to send a GET request that I think should return information (in this case something like localhost:12345/api/WebAPI), nothing happens. The browser/http client just gets stuck loading.
Try putting a [HttpGet] above public IEnumerable<string> Get()
It turns out the API Controller was being served on a different port. -.-

404 Errors for WebAPI - Registering routes in HttpModule not working

I am trying to add WebAPI endpoints to an existing forms application but I am getting 404 errors.
I cannot use the Global.asax Application_Start() to register the api routes as suggested by Microsoft here because the current application already has a compiled customization of the Global class which inherits from HttpApplication and they did not mark any of the methods as virtual. doh!
I am trying to load the routes using an HttpModule. I am getting 404 errors for the following URL:
https://example.com/webapplication/myapi/Authorize/User
Module code:
using System;
using System.Web;
using System.Web.Http;
public class MyHttpModule : IHttpModule
{
private static bool HasAppStarted = false;
private readonly static object _syncObject = new object();
public void Init(HttpApplication context)
{
//https://stackoverflow.com/a/2416546/579148
if (!HasAppStarted)
{
lock (_syncObject)
{
if (!HasAppStarted)
{
GlobalConfiguration.Configure(config => RegisterRoutes.Load(config));
HasAppStarted = true;
}
}
}
}
#region IDisposable Implementation
#endregion
}
My registration class is in a standalone library:
using System.Web.Http;
public static class RegisterRoutes
{
public static void Load(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "myapi/{controller}");
}
}
And my controller:
using System;
using System.Web.Http;
using MyLibrary.Models;
[Route("myapi/[controller]/[action]")]
public class AuthorizeController : ApiController
{
[HttpGet, ActionName("User")]
[AllowAnonymous]
public WebUser GetUser()
{
WebUser user = new WebUser();
user.Key = Guid.Empty.ToString();
return user;
}
}
And finally the web.config:
<configuration>
<!--...-->
<system.webServer>
<!--...-->
<modules>
<add name="MyModule" type="MyLibrary.MyHttpModule" />
</modules>
<!--...-->
</system.webServer>
<!--...-->
<configuration>
The webapplication is its own IIS application (its own Global.asax and web.config). I am on Windows 10, CLR version v4.0, and Managed Pipeline is Integrated.
I've tried several other options described here, here, and here but have not had anything but 404s.
TIA!
You are mixing up frameworks. [Route("myapi/[controller]/[action]")] is for asp.net-core while your code appears to be for asp.net-web-api
A few suggested changes.
Module code can be simplified
GlobalConfiguration.Configure(RegisterRoutes.Load);
Since attribute routing is configured
config.MapHttpAttributeRoutes();
Use the correct attributes on the APIController and action
[RoutePrefix("myapi/Authorize")]
public class AuthorizeController : ApiController {
[HttpGet, ActionName("User")]
[Route("user")] //GET myapi/authorize/user
[AllowAnonymous]
public IHttpActionResult GetUser() {
WebUser user = new WebUser();
user.Key = Guid.Empty.ToString();
return Ok(user);
}
}
Turns out the problem was in the MapHttpRoute() method call. It seems that the routing does not like not having a value for the defaults and constraints parameters. I updated the map call to this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: Constants.ApiBaseRoute + "/{controller}/{action}",
defaults: new { },
constraints: new { }
);
I also had to add the action template parameter. And I removed the route attributes on the controller.

Attribute Routing: "Not a valid ODataPath Template"

Ive been struggling with this all day and i think ive reached the end of all the answers ive seen on this. Maybe im special, or maybe im doing something stupid.
I recently upgraded from V3 to V4 (i think). Im using the System.Web.OData namespace which should be fine.
Here is my WebAPIConfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Routing;
using System.Web.OData.Routing.Conventions;
using GizmoAPI.Models;
namespace GizmoAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Counterparty>("Counterparties");
config.Select().Expand().Filter().OrderBy().MaxTop(null).Count();
config.EnableDependencyInjection();
config.MapHttpAttributeRoutes();
config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
config.AddODataQueryFilter();
var cors = new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:56248", "*", "*");
config.EnableCors( cors);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
config.EnableSystemDiagnosticsTracing();
}
}
}
and here is a basic controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.OData;
using System.Web.OData.Routing;
using GizmoAPI.Models;
namespace GizmoAPI.Controllers
{
public class CounterpartiesController : ODataController
{
private GizmoEntities db = new GizmoEntities();
// GET odata/Counterparties
[EnableQuery]
public IQueryable<Counterparty> GetCounterparties()
{
return db.Counterparties;
}
// GET odata/Counterparties(5)
[EnableQuery]
[ODataRoute("{key}")]
public SingleResult<Counterparty> GetCounterparty([FromODataUri] int key)
{
return SingleResult.Create(db.Counterparties.Where(counterparty => counterparty.CounterpartyID == key));
}
Then im trying to call the URL as http://localhost:60965/odata/Counterparties/101
or
http://localhost:60965/odata/101
or really anything at this point. I feel like there is some sort of configuration that im missing to activate it. I get the error "The path template '{key}' on the action 'GetCounterparty' in controller 'Counterparties' is not a valid OData path template. Resource not found for the segment '{key}'."
Did you try renaming your method to GetCounterParties([FromODataUri] int key)
and removing the OdataRoute Attribute?
This is not a 100% fix to my problem since i added odata as a tag.
Comparing the ODataController with the ApiController (WebAPI2.2), i couldnt find any reason not to switch to the latter.
So i changed my controller to inherit APIController, and switched all references of odata to the WebAPI version. In fact, the code above is almost identical with the exception of the aforementioned controller and the ODataRoute now becoming simply "Route". The code compiles completely fine and is far more manageable. I can even use the odata filters if the return type of my action is iqueryable.

Web API call not reaching?

i am using route prefix in my api
[RoutePrefix("api/currencies")]
public class DefCurrencyController : ApiController
{
[HttpGet, Route("")]
public List<DefCurrency> GetAllCurrencies()
{
return DefCurrency.AllDefCurrency;
}
}
my webapi config file
namespace ERPServices
{
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 }
//);
}
}
}
i am trying to reach or acess the GetAllCurrencies() using
http://localhost:1865/api/currencies
it returns error
HTTP Error 404.0 - Not Found The resource you are looking for has been
removed, had its name changed, or is temporarily unavailable.
what should i do to test my controller api ?
Ditch the RoutePrefix attribute on the controller and just declare the route you want on the method:
public class DefCurrencyController : ApiController
{
[HttpGet, Route("api/currencies")]
public List<DefCurrency> GetAllCurrencies()
{
return DefCurrency.AllDefCurrency;
}
}
Route prefix is for where you want to declare a portion of the route to apply to all methods in the controller (e.g. they are in an area).
Also, you don't need HttpPost here, this should be GET only.
You should also check that in your WebApiConfig you are calling config.MapHttpAttributeRoutes(); before any convention based routing.
Please try below of test the API
http://localhost:1865/api/currencies/GetAllCurrencies
There are several things required to make WebAPI work.
Add this is you project:
using System.Web.Http;
namespace WebConfig
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
}
}
}
And in your Global.asax file, add this in the Application_Start to call the Register method:
GlobalConfiguration.Configure(WebApiConfig.Register);
Also, in the web service, try changing for the following values to test the routing:
[RoutePrefix("api")]
public class DefCurrencyController : ApiController
{
[Route("currencies")]
public HttpResponseMessage Get()
{
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
}

What is the difference between AttributeRoutingConfig and RouteConfig in MVC5?

To understand the code behind the AttributeRoutingConfig I'm trying to recreate it using RouteConfig
AttributeRoutingConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using AttributeRouting.Web.Mvc;
[assembly: WebActivator.PreApplicationStartMethod(typeof(SimplestAuth.AttributeRoutingConfig), "Start")]
namespace xyz
{
public static class AttributeRoutingConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapAttributeRoutes();
}
public static void Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
RoutingConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace xyz
{
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 = "login", id = UrlParameter.Optional }
);
}
}
}
I'm looking for information to understand the differences and similarities between the two techniques. Thank you.
They both do essentially the same thing:
They register your routes to the RouteTable.
The first code sample you have above utilizes AttributeRouting so it does an assembly scan.
The second code sample you have utilizes the RouteTable directly, so it is a much more manual looking process.
Hope that helps.

Categories

Resources