WebApi is not Working in ASP.Net - c#

I am New in Asp.Net and tried to develop a small Web API in learning process.
WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
TopicsController.cs
namespace MessageBoard.Controllers
{
public class TopicsController : ApiController
{
private IMessageBoardRepository _repo;
public TopicsController(IMessageBoardRepository repo)
{
_repo = repo;
}
public IEnumerable<Topic> Get()
{
var topics = _repo.GetTopics()
.OrderByDescending(t => t.Created)
.Take(25)
.ToList();
return topics;
}
}
}
Actually i am watching PluralSight tutorials.
http://localhost:50031/api/v1/topics
this Url is not working in Browser not in Fiddler 4.
all references are added. i have also done Build Solution but its not working and their is no error showing in the code.

One last step to enable Web Api which looks like you're missing is enabling Web API in the Global.asax file by adding the following line of code to the Application_Start() method:
WebApiConfig.Register(GlobalConfiguration.Configuration);
Also, please don't use the port number from the PluralSight tutorial.You need to run the web application project from your instance of Visual Studio and when it opens up in the browser you will see which port is assigned to YOUR api service.So if you see that it assigned port 12345 for example you would call the following URL to access the service action:
http://localhost:12345/api/v1/topics

Add attribute routing to controller
[Route("api/v1/topics")]
public IEnumerable<Topic> Get()
{
var topics = _repo.GetTopics()
.OrderByDescending(t => t.Created)
.Take(25)
.ToList();
return topics;
}

Related

ASP MVC 4 + Web API

I have ASP MVC 4 project and the Web API.
I wanna use Web API from the main application. i did this:
WebAPI Project
WebApiConfig.cs
public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));
}
Global.asax
protected void Application_Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
}
StatisticsController.cs
public class StatisticsController : ApiController {
TopUserFactory topUserFactory = new TopUserFactory();
// GET api/statistics/topUsers
[ActionName("topUsers")]
public List<TopUser> Get() {
return topUserFactory.Top10Users();
}
}
But nothing happens when i go for localhost:31003/api/statistics/{topUsers}
How to use WebAPI project from other project?
When working with multiple sites locally they will have different port numbers.
You can check the port numbers by clicking the IIS Express icon on your taskbar:
You can change the port number by adding a configuration:
Changing project port number in Visual Studio 2013
your code looks ok. it's very easy to get the routes wrong with WebAPI, ensure you're doing a parameter-less GET to http://localhost:31003/api/statistics/topUsers
failing that, use this tool: https://www.nuget.org/packages/routedebugger/

custom error pages for non existent controllers in apiController

I have created a MVC web API with MVC 5 controller for managing CRUD operations.
Here is the snippet of my API controller:
public class UserController : ApiController
{// GET api/<controller>
public IEnumerable<User> GetAllUsers()
{
UserRepository urepo = new UserRepository();
return urepo.UserList(0);
}
public User GetUserByID(int userID)
{
UserRepository urepo = new UserRepository();
var userDetails = urepo.UserList(userID);
return (from n in userDetails where n.UserId == userID select n).SingleOrDefault();
} }
and here is my WebAPIconfig file
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
When I access this controller from URL say localhost/api/User/GetAllUsers
it is returning all users as expected.
But if i try to access in other way say localhost/api/User which is not there , will throw file not found error and show default error page.
what i need is instead of this default error page custom error page need to be displayed.
How this can be achieved?
Let's say that you are developing a HTTP RESTful application using ASP.NET Web API framework. In this application you need to handle HTTP 404 errors in a centralized location.
This Blog might help you in finding what you need.
Handling HTTP 404 Error in ASP.NET Web API

asp net start angular app

Maybe this is answered before but I couldn't find it. If this is the case a good link will be great.
I'm developing an angular application in top of an ASP.NET app. I communicate them through a restful service. The problem is when I run from visual studio my app (using IIS) it goes to url
http://localhost:51061/
As I can't get into this page i get an error 403 forbidden. I want that when I push run inside visual studio my app start in.
http.//localhost:51061/AngularApp/
Global.asax.cs
namespace WebApi {
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
WebApiConfig.cs
namespace WebApiPrC
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "backend/api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Thank you
Have you looked at ""Project > Properties > Web > Start Action" section?
You can specify however you want the app to start, e.g. "Current Page", "Specfic page" and "Start URL" etc. I guess you want to enter the url to "Start URL" box.
Webapi is a framework for resource transmission between server and client (data only) and for views routing you have set up Angular routing .
In this case,angularApp application angular routing is useful like :
AngularApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'xxx.html',
controller: 'xxxcontrollername'
}).
otherwise({
redirectTo: '/login.html'
});
}]);
Hope So its help you.

MVC 4 Web Api 404

I have looked all over for some kind of soultion for this and it seems I have it setup correctly and followed all corrections in other questions.
When calling "http://localhost/en/api/cart/get" I get:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/en/api/cart/get'.","MessageDetail":"No type was found that matches the controller named 'cart'."}
...when trying to access a ApiController setup in an EPiServer CMS/Commerce 7.5+ solution.
The Controller looks like this:
public class CartController : ApiController
{
[HttpGet]
public string Get()
{
return "OK";
}
}
In Global.asax.cs i have this:
protected void Application_Start()
{
RegisterApis(GlobalConfiguration.Configuration);
And the RegisterAPis looks like this:
public static void RegisterApis(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
"Api", // Route name
"api/{controller}/{action}/{id}", // URL with parameters
new { id = RouteParameter.Optional } // Parameter defaults
);
config.Routes.MapHttpRoute(
"LanguageAwareApi", // Route name
"{language}/api/{controller}/{action}/{id}", // URL with parameters
new { id = RouteParameter.Optional } // Parameter defaults
);
// We only support JSON
var appXmlType = GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
On the same machine I have the EPiServer Commerce starterkit running i IIS and the code for registering the api controllers is the same. That site runs fine and the api calls can be made correctly but on my site all I get is 404.
So I am probably missing some configuration but I can't for my life figure out what it is. The weird part is that on my site I'm running the EPiServer ServiceApi which creates the /episerverapi Web Api mapping and that works just fine.
Anyone got any clues on why I can't get my APiControllers to work?
In Web API the http verb help the framework to find the right action to be executed and return a result. For sample, in a case of a get method, you just call the controller by get http verb:
http://localhost/en/api/cart
It will bind a Get action method in the Cart controller class. It is valid for a Post, Put, Delete methods too. Keep the default route of asp.net web api
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Try calling just
http://localhost/en/api/cart
In WebAPI if the name of the method matches a HTTP verb then it calls that method when that verb is used on that controller.

ASP.NET MVC4 Web API Controller Stuck on One Route

I created a new ASP.NET MVC4 Web Api Project. In addition to the default ValuesController, I added another controller, ScenarioController. It has the exact same methods as ValuesController. But for some reason, it behaves differently.
/api/values/ => "value1","value2"
/api/values/1 => "value"
/api/scenario/ => "value1","value2"
/api/scenario/1 => "value1","value2"
^^^^^^^^^^^^^^^^^
should return "value"!
Using breakpoints, I know that /api/scenario/1 actually gets sent to the public IEnumerable<string> Get(), not the expected public string Get(int id). Why?
For reference, here are the relevant files (these are pristine default mvc4-webapi classes, haven't modified anything):
Global.asax.cs
namespace RoutingTest
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
WebApiConfig.cs
namespace RoutingTest
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{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();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
}
}
ValuesController.cs
namespace RoutingTest.Controllers
{
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";
}
}
}
ScenarioController.cs (yes, it's in the Controllers folder)
namespace RoutingTest.Controllers
{
public class ScenarioController : ApiController
{
// GET api/scenario
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/scenario/5
public string Get(int id)
{
return "value";
}
}
}
Gremlins. Thanks to #Pete Klien for verifying that the code does work outside my machine. Here's what I did.
Experienced problem of Controller only using 1 method for Get in original project.
Created new Web Api project, with code that I posted in the question. Same symptom.
Clean Project, Rebuild All, still no dice.
Reboot machine, clean, rebuild, try again, no dice.
Create new Web Api project in new solution, success!
I tried your code just now and got the expected result:
> curl http://localhost:53803/api/values
["value1","value2"]
> curl http://localhost:53803/api/values/1
"value"
> curl http://localhost:53803/api/scenario
["value1","value2"]
> curl http://localhost:53803/api/scenario/1
"value"
>
(By the way, there is no requirement that it be in the Controllers folder. HttpConfiguration.Routes.MapHttpRoute simply finds all your classes that inherit from ApiController.)
I am not being sarcastic when I suggest that you Rebuild All and try again.
I was having this issue and could not get anything to work. Finally I changed the port on the IIS Express Project Url setting and all is back to normal. It was localhost:57846. I just made it localhost:57847 and all is back to normal.

Categories

Resources