Web API controller in subfolder not being found with attribute routing - asp.net-mvc

I have a controller in this folder structure:
Site
-Controllers
--API
---EventsController.cs
The EventsController.cs contains this:
[RoutePrefix("api")]
public class EventsController : Controller
{
[Route("event")]
public ActionResult Index()
{
return View("~/Views/Home/Index.cshtml");
}
The WebApiConfig.cs contains this:
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 }
);
}
When I run the site from Visual Studio and try to access http://127.0.0.1:8080/api/event I see nothing but this error:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://127.0.0.1:8080/api/event'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'event'.
</MessageDetail>
</Error>
If I comment out the config.Routes.MapHttpRoute line to make WebApiConfig.cs as the following, the URL above works:
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 }
//);
}
What am I doing wrong? What is it that causes the attribute routing to fail when the DefaultApi route is configured? I have tried placing it before/after the config.MapHttpAttributeRoutes(); and neither works.
As an aside, I have manually built up this project while reading the following article, which has the same structure of MVC/Web API project and which does work. I just can't figure out what I've done differently.
http://www.codemag.com/Article/1605081

Thanks to #phil-cooper the answer was to inherit the correct base class in the api controller.

Related

How to correctly configure Web-API2 Routes to accept strings that go to an object?

I have a .NET project that has a Web API portion to it which should be accepting requests externally. The action accepts an object which is then used further on. The problem is when testing with postman app, the action is hit but variables are not passed.
Here is an example of my URL in postman: http://localhost:12345/api/login/postlogin?Username=un&Password=pw
I have tried using [frombody], this would work only if I am receiving a single string. My application will be utilizing lots of data passing back and forth. I have also tried multiple solutions on StackOverflow including [FromUri]. The post is still null.
WebAPi.Config snippet:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Action within Controller:
// POST: api/postLogin/
[AllowAnonymous]
[System.Web.Http.HttpPost, System.Web.Http.Route("postlogin")]
public async Task<IHttpActionResult> PostLogin(LoginDTO login)
{
}
The expected result as stated early is to receive variables as an object then use them within the action.
Your configuration for Routing is correct. You should use [FromBody] attribute to the parameter, because this is a POST request.
you should never use GET request to do authentication!
public async Task<IHttpActionResult> PostLogin([FromBody]LoginDTO login)

How do I initialize a webhook receiver in ASP.Net MVC

I'm following this guide here for installing and using webhooks in ASP.Net MVC, but it looks like this guide is for a wep api type project. I'm using a MVC type project and there is no Register method, unlike a API project. In MVC we have a RegisterRoutes method. So how do I register my webhooks in MVC?
an API project that uses Register and config, my ASP.Net MVC site doesn't have this.
MVC uses RegisterRoutes
UPdate
Here I added a web api controller and the code I posted below is whats in the web api controller. I included the nuget packages for webhooks, the registration in global.asax.cs and in the register method. But I'm still having problems reaching the code 'ExecuteAsync' no breakpoints are being hit
public class StripeWebHookHandler : WebHookHandler
{
// ngrok http -host-header="localhost:[port]" [port]
// http(s)://<yourhost>/api/webhooks/incoming/stripe/ strip receiver
public StripeWebHookHandler()
{
this.Receiver = StripeWebHookReceiver.ReceiverName;
}
public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
// For more information about Stripe WebHook payloads, please see
// 'https://stripe.com/docs/webhooks'
StripeEvent entry = context.GetDataOrDefault<StripeEvent>();
// We can trace to see what is going on.
Trace.WriteLine(entry.ToString());
// Switch over the event types if you want to
switch (entry.EventType)
{
default:
// Information can be returned in a plain text response
context.Response = context.Request.CreateResponse();
context.Response.Content = new StringContent(string.Format("Hello {0} event!", entry.EventType));
break;
}
return Task.FromResult(true);
}
}
You can mix web api controllers in your MVC project. When you add web api controllers, you will have a WebApiConfig.cs file in your App_Start where you will definie the routing for web api. That is where you can call the InitializeReceiveStripeWebHooks method after adding the necessary nuget packages to your project.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Load receivers
config.InitializeReceiveStripeWebHooks();
}
}
When you create a new project, Visual studio present you with different project templates. You can select the WebApi one which includes MVC and Web Api support. But if your project is created using the MVC template, it will not have the web api support by default. In that case, you can manually add it by following these steps.
Step #1
Create a new class called WebApiConfig.cs in the App_Start folder. Have the below content in that class
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Step #2
Now go to global.asax and update the Application_Start event to include a call to the Register method in our newly created WebApiConfig class.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register); // This is the new line
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Now you can right click on project and add new WebApiController classes and web api's should work now.

WebApi Routing - map url to api

I've been googling for about an hour and not found an example so I thought I'd ask here.
I am replacing a standard mvc controller with a webapi and having problems with the routing, I've changed the names because of the organisation but they are still valid.
my webapi is currently called SystemAPI in the controllers folder - I want it to have a different name that the url that points to it ideally.
The url I need to point to it is /v1Controller/{id}
I cant change the v1Controller url as it is a fixed point with apps I have no control over
my current coding attempt is
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DocumobiApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "V1Controller",
routeTemplate: "v1Controller/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
to which I get the response
"message":"No HTTP resource was found that matches the request URI 'http://localhost:38685/v1Controller'.","messageDetail":"No route providing a controller name was found to match request URI 'http://localhost:38685/v1Controller'"}
I'm sure its something fairly obvious but cant for the life of me figure it out.
Cheers,
Steven
As the following error message says, a route match should result in providing value for the controller route variable which Web API depends on for selecting a controller.
No route providing a controller name was found to match request URI 'http://localhost:38685/v1Controller
So you could modify the route like below(notice the default value for controller variable):
config.Routes.MapHttpRoute(
name: "V1Controller",
routeTemplate: "v1Controller/{id}",
defaults: new { id = RouteParameter.Optional, controller="SomeControllerHere" }
);
Make sure your action method on your controller has an id with a default value.

Non Api routing with SPA and Web Api

I have been trying for a few days to solve this problem so I may in fact be trying to solve the wrong problem or don't know the right terms to search so here goes.
I'm creating a SPA with AngularJS and Web Api (4.5). All of my views are client side. So the server doesn't know all the possible routes that may become present in the URI. This isn't a problem until a user uses one of the browser controls (back, forward, refresh, history) and the server attempts to route the requested URI.
My thoughts on dealing with this have centered around mapping all non API routes to the root of the application.
So I would like to either, know the correct syntax for MapHttpRoute to pick up any route that does not attempt to reference controllers (API's) or if there is a better method for dealing with this problem.
public static void Register( HttpConfiguration config )
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//
// This doesn't work
//
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{*catchall}"
);
}
This XML file does not appear to have any style information associated with it. The document tree is shown below.
No HTTP resource was found that matches the request URI 'http://localhost:9234/login'.
No route providing a controller name was found to match request URI 'http://localhost:9234/login'
Not a good idea, just workaround
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{*catchall}",
defaults: new { controller = "Spa"}
);
[AllowAnonymous]
public sealed class SpaController : ApiController
{
public HttpResponseMessage Get()
{
var indexHtml = HostingEnvironment.MapPath("~/index.html");
var stringContent = new StreamContent(File.OpenRead(indexHtml));
var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = stringContent};
return response;
}
}

No HTTP resource was found that matches the request URI

I just deployed my MVC app to a subdomain and I just can't get webapi to work.
Accessing locally:
localhost:40052/api/apiEmpreendimento/GetObjects
works just fine, but accessing the following online:
http://subdomain.mysite.com/api/apiEmpreendimento/GetObjects
Gives me
{"Message":"No HTTP resource was found that matches the request URI 'http://subdomain.mysite.com/api/apiEmpreendimento/GetObjects'."}
App_Start/WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional }
);
}
}
Any tip is much appreciated.
Thanks
I thought it's about new WepApi. MVC understands it like WebApi controller, Microsoft Reserved Api Controlller for their selves, I changed my Controller name With MyApiController and problem solved.

Resources