OWIN WebApp.Start causing all code to be run 3 times - c#

Hi im currently working on running some simple webapp code inside another .net program. But it seems whenever i run the WebApp.Start() function all my code suddenly run 3 times instead of 1.
Example:
"First debug" appears once.
"Configration called" appears 3 times in a row.
"http://127.0.0.1:8080/: Server running at {0}" appears 3 times in a row.
I cant seem to find any information on this on the interwebs, so hoping someone here has experienced my pain,
Main class:
static void Main()
{
Debug.WriteLine("First debug");
string baseAddress = "http://127.0.0.1:8080/";
WebApp.Start(baseAddress);
Debug.WriteLine("Server running at {0}", baseAddress);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
Debug.WriteLine("Configration called");
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
}
}

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

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/

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.

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

how to fix this error WebApiConfig in Global.asax?

There's a great thread running here:
How to add Web API to an existing ASP.NET MVC (5) Web Application project?
Unfortunately, for me is having an error on WebApiConfig in Global.asax, so how can i fix this error i even installed nugets.
The name 'WebApiConfig' does not exist in the current context
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
WebApiConfig
public 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 }
);
// WebAPI when dealing with JSON & JavaScript!
// Setup json serialization to serialize classes to camel (std. Json format)
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}
As you copied code from other project , you are merging web api in existing mvc project so many time two project have different namespace so you have to add namespace or change namespace of webapiconfig.

Categories

Resources