asp net start angular app - c#

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.

Related

How to activate cors in a asp.net website (razor 3)

I am pretty new to ASP.NET Website programming. I have an node js express application where I need to make requests to. This currently doesnt works from my asp.net site because i dont have cors enabled. I hope you can help me and if I am just beeing stupid and configured my website wrong or forgot to add a controller please let me know.
I tried adding cors package via nuget and adding it to the web.config.
In the Solution Explorer, expand the WebApi project. Open the file App_Start/WebApiConfig.cs, and add the following code to the method WebApiConfig.Register.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Then add the attribute [EnableCors] to the desired controller:
namespace MyProject.Controllers
{
[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}

Call WebAPI GET yielding 404 not found

VS 2017, New, Project, C#, ASP.NET Web app, ASP.NET 4.5.2 Empty Templates.
Unchecked folder and reference for Webforms, MVC and WebAPI. Later added MS WebApi v5.4.2 via Nuget.
Manually added "Controllers" folder.
xController.cs:
namespace v1.MyApiCallTheirApi.api
{
public class xController : ApiController
{
// GET api/<controller>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
index.html:
<body>
<input type="button" value="Go" onclick="go()"/>
<script type="text/javascript">
function go()
{
alert("lafdla");
$.ajax({
type: "GET",
url: "/api/x",
success: alert("ok")
});
}
</script>
</body>
$.ajax call always returns 404. Already check this, that, and many others. So far my only suspect is it may need a Global.asax for routing config, but I assume after adding API it should auto-add some hidden routing for me.
Right now your application doesn't knows how routes are created. MVC cannot know automatically unless you provide the pointers as to where each type of code is located.
Hence two ways out here (using GlobalConfiguration instance):-
a) Convention based, use map route method. No other place requires any further change.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
b) Use attributes on controller methods to define actual routes. Then add the route attribute on each action method
config.MapHttpAttributeRoutes();
Over action
[Route('api/myentity/get')
public entity GetEntity() { }
As for adding the package, it only provides you the relevant dlls required for WebAPI, doesn't makes any more changes
You can define the default action of the controller also by the Action attribute [HttpGet("")].
You need to update your action:
// GET api/<controller>
[HttpGet("")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
As a tip Postman is a nice tool to test your api requests, which is also recommendet by the .NET documentation, see here.
Summarize the WHY and SOLUTION of my problem:
Global.asax
API Routing registration via App_Start
Attribute and Convention routings can't mixed together
Once going Attribute you have to declare attribute for each method.
Although Api controller can be placed anywhere/folder and can be named anything without "Controller" suffix, it must have the "Controller" suffix for class, i.e. public class v1Controller : ApiController, just public class v1 : ApiController won't work.
Global.asax is optional but it's like _init() of a project, so is a must here because API needs routing. Whether this Api is invoked by in-project or out-of-project, as soon as it's hit the built-in App_Start init everything of the project.
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
API routing registration defined in a class typically in App_Start, convention name is WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Either this Attribute Routing
config.MapHttpAttributeRoutes();
// Or this conventional Routing, but not together.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Adding a new package from Nuget won't auto-config/add necessary items
to project.
MS WebApi is developed based on MVC routing, it's confused if MVC is needed, here is a good reading. Answer is No, you don't need MVC in order to do WebApi.

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/

WebApi is not Working in ASP.Net

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;
}

Attribute routing not working MVC5

This is a long post. I am using attribute routing as described here:
http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#enabling-attribute-routing
I have placed in WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
+ config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
}
in Global.asax.cs
AreaRegistration.RegisterAllAreas();
+ //WebApiConfig.Register(GlobalConfiguration.Configuration);
+ GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
and I am using a webapi controller with:
public class HelloController : ApiController
{
[Route("Services/test/Application/{id}")]
public string GetTest(int id)
{
return "1";
}
}
I am using Postman Chrome extension to test. On my own computer when I test in Visual Studio this is working perfectly: http://localhost:6296/Services/test/Application/12
and returns the expected result, but after I deploy it on a site, it does not work: http://www.mytest.com/Services/test/Application/12 (tested even on the server localhost: http://localhost/Services/test/Application/12)
and returns:
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: /Services/test/Application/12
The reference System.Web.Mvc (version 5.2.3.0) is marked as "copy local = true". No authorization is used. Classic webapi controlls work perfectly on the server and locally.
Question: what could be wrong and where should I start looking?!
Add this to your WebApiConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}

Categories

Resources