How to hide Controllers routes in ASP.NET WebApi - asp.net

I have a WebApi project and I got myself in this situation. Let's say that I have a Route :
[Authorize]
[RoutePrefix("api/v1/GG")]
public class StorkUserController : ApiController
{
private IAuthenticationManager Authentication
{
get { return HttpContext.Current.GetOwinContext().Authentication; }
}
[Route("UpdateUser")]
[HttpPost]
So When I start the application, if i directly type in my browser this route :
http://localhost:52494/api/
I will get this Error with some details :
Or if I navigate to http://localhost:52494/api/v1/GG I get :
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:52494/api/v1/GG/'.","MessageDetail":"No type was found that matches the controller named 'v1'."}
How to prevent for this Happen since these routes could be easily to be found, and instead of it, show something like "ERROR 404"! Thanks!

Related

404 Not Found when accessing a Web API method

I need this method to return an integer value:
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpPost("ByPayment")]
public int Payment(string accountId, string mount, string shenase)
{
return 21;
}
}
When I go to the following address:
http://localhost:1070/api/values/Payment/ByPayment?accountId=258965&mount=85694&shenase=85456
I get the following error:
What's the problem? And how can I solve it?
I thing you wanted to send Get request with query string parameters.
1. Change the 'HttpPost' to 'HttpGet'
[HttpPost("ByPayment")] to [HttpGet("ByPayment")]
2. Also change your request url, Its not correct.
http://localhost:1070/api/values/Payment/ByPayment?accountId=258965&mount=85694&shenase=85456
to
http://localhost:1070/api/Values/ByPayment?accountId=258965&mount=85694&shenase=85456
Updated code
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet("ByPayment")]
public int Payment(string accountId, string mount, string shenase)
{
return 21;
}
}
I suggest please read this tutorial to understand the basic of webapi.
There could be more reasons why you get the 404. But there is one thing that's definitely wrong - you are sending GET requests to a method that's marked with [HttpPost("ByPayment")] (which means it only responds to POST requests.
I don't know what you intended to do but you either have to change it to [HttpGet("ByPayment")] or use a REST client that can make POST requests (e.g. REST Easy.
Other reason could be that your controller has a wrong name. It should be called PaymentController.

No type was found that matches the controller named

UPDATE: I unloaded the project and re-did it again and it worked.
I'm trying to create a WebApi, my build works fine and I get the error message "No type was found that matches the controller named" when I try to go to URI
This is how my webapiconfig 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 }
);
}
}
And below is my controller,
public class ClientController : ApiController
{
public List<Client> Get()
{
ICRepository repository = new CRepository(new CContext());
return repository.GetAllClients().ToList();
}
And this is how my global.asax.cs file looks like,
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
I'm trying to browse to the url "http://localhost:50662/api/client"
The complete error is as below,
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:50662/api/Client'.No type was found that matches the controller named 'Client'.
My question is different from what it's been marked as duplicate of, the question uses just controller which is MVC and mine is "ApiController" and I did read that before creating this. Also, the marked answer there is similar to what I have in here and my problem still exists.
Any help would be highly appreciated. I'm really lost.
I was getting the same error:
Error><Message>No HTTP resource was found that matches the request URI 'http://localhost:53569/api/values'.</Message><MessageDetail>No type was found that matches the controller named 'values'.</MessageDetail></Error>
By default when I created new controller in asp.net web forms application, it was like this:
ValuesController1 : ApiController
I just simply removed "1", and make it:
ValuesController : ApiController
I don't know if it is a bug or whatever, but it works for me.
you are calling WebApiConfig twice.
WebApiConfig.Register(GlobalConfiguration.Configuration);
GlobalConfiguration.Configure(WebApiConfig.Register);
Remove one of them. if you are using Web Api Version >= 2.0, then remove the first one, otherwise remove the second one.
Edit 1
I think your issue may be similar to this Answer
You might be missing some reference libraries, may not be directly related to Your Controller or API, but the way Web Api finds the Controller, is it go through all assemblies referenced by the application and search for types matching a predicate.
Although it isn't the cause of your problem, mine was actually caused by adding a new item of type class through Visual Studios context-menu and not a Controller.
The generated file had the following structure:
class foo
{
}
I extended the class to inherit from ApiController, but forgot to mark it as public
This is the correct version:
public class FooController : ApiController
{
public string Get(string name="Bar")
{
return $"Hello {name}"};
}
}
Right now I am facing a very similar issue. My error message was No type was found that matches the controller named 'odata'. It seems really strange to me, that it seems to be searching for a controller named ODataController or something like that. So I started looking for the real issue. In my case, it was the fact, that I had forgotten to include a public parameterless contructor to the controller class. I added it and the error went away immediately.

Web API routing for non-REST services

I'm designing a webservice which has nothing to do with REST. It backs up a single-page application and currently must implement three simple methods:
public class ImportController : ApiController
{
[HttpPost]
public string[] Parse(string source) { ... }
[HttpPost]
public ConvertResponse Convert(ConvertRequest request) { ... }
[HttpGet]
public object GetHeaders() { ... }
}
It worked pretty well when I was using Controller, except for one thing: I needed to convert all returned JSON data to camelCase. I found a pretty reasonable solution on the web which used CamelCasePropertyNamesContractResolver, but it was only applicable to WebApi controllers since MVC controllers that return JsonResult always use JavascriptSerializer and ignore this configuration.
When I switched the base class to ApiController, the routing broke: GetHeaders works, but other methods return a 404 error!
My route configuration is as follows:
routes.MapHttpRoute(
name: "ImportParse",
routeTemplate: "import/{action}",
defaults: new { controller = "Import" }
);
The successful request (AngularJS):
var baseUrl = 'http://localhost:3821/';
$http.get(baseUrl + 'import/getHeaders').success( ... );
The unsuccessful request:
$http.post(baseUrl + 'import/parse', { source: 'test' }).success( ... );
Error:
message: "No HTTP resource was found that matches the request URI 'http://localhost:3821/import/parse'."
messageDetail: "No action was found on the controller 'Import' that matches the request."
How do I define the correct routing rules for those methods?
Most probably Web Api is looking for a Parse action that supports HttpPost and has object parameter. Because you post object, but not a string, that is why you get 404.
To solve this problem try to send :
$http.post(baseUrl + 'import/parse', 'test').success( ... );

No type was found that matches the controller named 'help'

I have been following this guide to add a help page to document my Web API project. My Controller is named HelpController and I have a route that I am trying to use to map the Index action to /Help. This is the only MVC controller in the project. Because the rest are Web API controllers, we removed the "/api" prefix from the default route in WebAPIConfig.cs.
The HelpController:
public class HelpController : Controller
{
public ActionResult Index()
{
var apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
return View(apiExplorer);
}
}
And route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "help",
defaults: new { controller = "Help", action = "Index"});
}
}
In Global.asax.cs
protected void Application_Start()
{
// ..
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// ..
}
But when I try to navigate to /help in the browser I get the following error message.
<Error>
<Message>No HTTP resource was found that matches the request URI 'http://localhost/ws/help'.</Message>
<MessageDetail>No type was found that matches the controller named 'help'.</MessageDetail>
</Error>
EDIT: The message contains /ws/help as the application is hosted at localhost/ws in IIS.
Does anyone know what could be causing ASP.NET to not find my HelpController?
UPDATE: If I change the order of RouteConfig and WebApiConfig registration calls in Application_Start I get a 404 instead.
protected void Application_Start()
{
// ..
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration);
// ..
}
The request for help is being matched by Web API's route as you have removed api from its route template. if a request matches a route, further probing is not done on rest of the routes.
You probably have the default order in Global.asax where Web API routes are registered first and then the MVC routes. Could you share how your Global.asax looks like?
EDIT:
Based on your last comment, if you install HelpPage nuget package, make sure that the order in your Global.asax looks like this:
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
I had this same error today.
<Error>
<Message>No HTTP resource was found that matches the request URI 'xxx'.</Message>
<MessageDetail>No type was found that matches the controller named 'xxx'.</MessageDetail>
</Error>
In my case after 2 days of debuging I finally solved it by setting the microsoft report viewer dll to "Copy to local". Makes no sense to me how it could be related, but maby this will help someone.
I was getting the same error:
Error><Message>No HTTP resource was found that matches the request URI 'http://localhost:53569/api/values'.</Message><MessageDetail>No type was found that matches the controller named 'values'.</MessageDetail></Error>
By default when I created new controller in asp.net web forms application, it was like this:
ValuesController1 : ApiController
I just simply removed "1", and make it:
ValuesController : ApiController
And it works, don't know if it is a bug or whatever, but it made big trouble for me.

How get user name in MVC WebAPI Controller

I have a Logon Controller Get method where I want to return the user id.
I am using basic authorization and all work fine but in the Get method I am not able to get the correct user id.
This is the code :
public class LogonController : ApiController
{
[BasicAuthorize]
public string Get()
{
int id = WebSecurity.CurrentUserId; // returns -1
return id.ToString();
}
}
My application is based on MVC 4 internet template with authentication mode="Forms"
I am not sure how to configure the two authentication modes even they seem to be working.
Any suggestion ?
Thanks

Resources