Basically I have an exe, that controls a pizzaria, it should be extended to allow users to choose a pizza slice from the web. The application I have, keeps track of what slices are available at the moment, and only show them on the site.
I've made an asp.net web api project and am hosting that inside my application.
(Owin, self hosting asp.net web api;-) My problem is how to configure the IAppBuilder, to go the normal MVC steps looking for my site, when the url, requested didn't go to an api controller.
public class Startup {
public static void Configuration(IAppBuilder app) {
app.UseStaticFiles();
var apiConfig = new HttpConfiguration();
apiConfig.MapHttpAttributeRoutes();
app.UseWebApi(apiConfig);
// THIS IS WHERE I NEED THE app to look through
// my MVC controllers, to get the view..
app.Run(async context => {
await context.Response.WriteAsync(" My First dummy OWIN App");
});
}
}
(I think I just need to figure out how to get the mvc controllers to get the request.. )
Thanks any help will be appreciated, with this, my first asp/web project in 15 years..
Related
I have one .NET Core MVC application that provides a dashboard to represent statistics and so on.
I would like to use this MVC application as a Middleware so that I can use it the same way than Hangfire, NSwag and so on.
So in my main project I would like to do the following:
Import my NuGet package (the Dashboard MVC Application)
app.UseDashboard(options...)
I already have a Middleware class inside my Dashboard MVC App with the following:
public static class JwtDashboardMiddleware
{
public static void UseMyDashboard(this IApplicationBuilder app)
{
// 1. Provide an endpoint(/ myDashboard)
app.Map("/myDashboard", app =>
app.Run(async (context) =>
{
string message = "Hello Middleware";
//2. This page contains a simple form, Submit the form to redirect to another for
await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(message));
}));
}
}
I also created a NuGet Package with the Dashboard MVC App and it is working, but in the Main Application and also in the in the Dashboard MVC App it cannot access the Views and so on.
So from the Middleware inside the Dasboard MVC app how do I access the controllers and how do I integrate this with other MVC applications to achieve the points mentioned above?
Btw. I also tried to redirect to the controller view, but the view is just not accessible ? Do I need to compile the views to be included in the NuGet package or how does this work?
The main question is: How do I use my controllers and views inside the Middleware?
You cannot embed whole MVC application into one static route.
NSwag for example, on the /swagger endpoint, serves a static html file, which is basing on swagger.json file generated from the API itself
I am following a tutorial on asp.net web api and mongodb here and on step 4 it talks about dependency injection and adding it to the start.cs in the ConfigureServices() method, however this doesnt seem to exist anymore. My web api templates startup.cs looks something like this...
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
So my question is where do I inject my DataAccess class to my web api project as a service? Thanks in advance.
As requested here is my api structure
under LGR.API is the auto generated folders and classes created by visual studios and starting a LGR.Datamodel is my custom class with my api stuff. Really new here... not sure if this correct at all. Feel free to critique with best practices as necessary
It looks like you've created an ASP.NET application, and your tutorial is for ASP.NET Core. Recreate your project and pick the "ASP.NET Core Web Application" template.
well, I am now learning aspnet core , I can't understand when does the application start its server(like IIS or KestrelServer),and how the server listen the httprequest and forwards the request to the application. can anybody help me? thanks
Well, let's start from beginning (As I couldn't figure out your knowledge about C#)
Every C# application must contain a single Main method specifying where program execution is to begin, so there it is, by default the templates have a Class Program where you can set the type of WebServer that you'll use, and tell the server to start listening for HTTP requests, something like:
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
var host = new WebHostBuilder()
.UseKestrel()
.UseConfiguration(config)
.UseStartup<Startup>()
.Build();
host.Run();
}
In AspNetCore and even in AspNet (MVC or WebApi) you can (and should) use OWIN (aka Katana or vNext, that are Microsoft's OWIN implementations for AspNet and AspNetCore respectively).
OWIN represents a Interface (just a specification), that tell how WebServers should comunicate with WebApplications. Normally it handle the Http Requests to a pipeline that you can plug Middlewares, like Authentication/Authorization, Log, Error Handlings and so on, and in the end of the pipeline you should plug your Web Application.
In AspNetCore you set your Middleware Pipeline by using UseStartup<MyStartupClass> in your Host configuration see Main method above and simple as that your Pipeline will handle every HttpRequest.
When building a MVC applications in AspNetCore (.UseMvc()) you are setting a middleware that tells your application to look for classes that inherit from Microsoft.AspNetCore.Mvc.Controller to look for RESTful entry points (HTTP GET, POST...)
This is just a simple overview, and you can learn a lot more looking in the documentation of this technologies. Just search for tags like Katana, vNext, OWIN, OWIN Middleware, OWIN Pipeline...
ASP.NET Core application anatomy is discussed here at this asp.net core introduction.
Some important text that answers your question is as follows from the tutorial:
An ASP.NET Core app is simply a console app that creates a web server in its Main method. Main uses WebHostBuilder, which follows the builder pattern, to create a web application host. The builder has methods that define the web server (for example UseKestrel) and the startup class (UseStartup). In the example above, the Kestrel web server is used, but other web servers can be specified. The Startup class is where you define the request handling pipeline and where any services needed by the app are configured. The Startup class must be public and contain the following methods:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
}
}
I guess this will help you to understand how asp.net core handles Http requests.
Thanks
I'm being tasked with the creation of an intranet web application. It will eventually consist of a SPA Frontend (probably Angular) sitting on top of a NancyFx API.
Frankly I have absolutely zero experience using Windows users for Auth, and since it's generally not recommended (rightly so), it can be hard to find concrete information on this.
I want to authorize users based on the user that is sending each request. However, I have no idea how I can access user information from each request context in Nancy. I've had a look at doing:
public class IndexModule : NancyModule
{
public IndexModule()
{
Get["/"] = parameters =>
{
var User = this.Context.CurrentUser;
return View["index"];
};
}
}
Unfortunately, this.Context.CurrentUser never seems to be populated and is always null.
How can I populate each request context with a Windows User?
Alternatively, am I doing it wrong? What is the recommended way of dealing with Windows Users in Nancy? I've been researching this for over two days, and I'm quite nervous about telling my boss that I don't know how to handle this rather essential issue.
Nancy provides the NancyContext type to provide you with context within which the call takes place.
Unfortunatelty Nancy does not contain the windows user out of the box. In fact, Nancy has no native knowledge of the IUserPrincipal type, which is what is typically used to represent windows identities.
The good news is that Nancy does integrate with Owin, and Owin provides it's own context which does contain this information, and additionally this will get injected into the Nancy context at no extra cost!
What you need to do to make this happen is install the Nancy.Owin nuget package and then make a call to the extention IAppBuilder.UseNancy() from the Owin "Startup" class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
// other owin config here...
// Register Nancy with Owin middleware...
app.UseNancy();
}
}
This will then enable you to access the Owin environment from the NancyContext like this:
var owinEnv = context.GetOwinEnvironment(); // context = your NancyContext
var windowsUser = (IPrincipal) owinEnv["server.User"];
Alternatively, if you don't fancy Owin, you could do this instead: https://stackoverflow.com/a/28976742/569662
I am trying to convert an existing ASP.NET Web API project (currently hosted in IIS) into one that can use the SelfHost framework. I'm a bit fuzzy on the actual details but understand I can run a self-host server in a console window and then run the service on top of it. The problem I'm having is that my project is an MVC project and not a console one. My familiarity with console/Windows apps is somewhat limited as I generally work with projects to be hosted in IIS.
What I'm a bit confused on is whether I need to convert my existing Web API project in Visual Studio into a new console application, or if there's a way to create another console application Project in the solution which can act as the web server for the Web API services, or rather if there's a way to add a console element with a Main() entry point to the existing MVC project (overriding the Global.asax entry point.)
Search didn't yield much information that helps me fill this knowledge gap. Hoping someone can point me in the right direction. Even at a high level.
I recently had to convert a Web API project into a self-hosted service using OWIN (on Visual Studio 2013). I did that as follows:
Manually added Program.cs and Startup.cs files at the root of the project. Both files containing code as described here: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api.
Went to the properties of the Web API project. On the "Applications" section, I stated "Output Type" as "Console Application", and set the "Program" class as the "Startup object".
Although not required, I slightly modified the using block within Program.Main() to look as follows:
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
if (response != null)
{
Console.WriteLine("Information from service: {0}", response.Content.ReadAsStringAsync().Result);
}
else
{
Console.WriteLine("ERROR: Impossible to connect to service");
}
Console.WriteLine();
Console.WriteLine("Press ENTER to stop the server and close app...");
Console.ReadLine();
}
Finally, instead of calling config.Routes.MapHttpRoute() multiple times within Startup.Configuration(), you can refer to the routes you already wrote for the Web API:
// Configure Web API for self-host.
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);