Use .NET Core MVC Project as a middleware - c#

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

Related

Use another controller from different project on asp.net core

We trying to rewrite out old project to form old mvc to the asp.net core mvc. we used to attach another mvc project as reference and called the controller without problem. but on the new asp.net core MVC it seems it need another work around
so the webapplication9 added webapplication1 as reference. and call the canary but it return 404. it worked on old mvc.
the controller just return the plain content
namespace WebApplication1.Controllers
{
public class CanaryController : Controller
{
public IActionResult Index()
{
return Content("Canary");
}
}
}
is there some part need to add to make webapplication9 able to call the webapplication1 controller?
on old MVC 5 we can just called it on URL http://webapplication9/Canary and it works.
on asp.net core it return 404 or not found
First, your other projects shouldn't be an Web application, but a normal PCL.
Second, after you reference it, you need to tell ASP.NET Core that it should look for controllers there. For that reason the Application Parts Api exists.
services.AddMvc()
.AddApplicationPart(typeof(CanaryController).GetTypeInfo().Assembly);
P.S. while the docs state it should work out of the box, when doing integration tests/unit tests on the controllers the .AddApplicationPart is still required, at least was the case in ASP.NET Core 2.0

Asp.net Identity with Code First in Asp.net MVC application using class library

I am trying to implement Identity Authentication using class library with code first in my asp.net MVC application.
At first I created test project with default selection "Individual User Accounts"
Using default templates with identity i found It creates some of the default files/classes like
IdentityModel.cs, IdentityConfig.cs(in APP_Start) & Startup.cs(partial class with anothe file in APP_Start Startup.Auth.cs),
AccountViewModel.cs, ManageViewModel.cs .
After that I searched for how to use identity related classes in Class Library, and using suggestions moved
all of above in class library project Names TestLib.
I have put IdentityModel.cs, IdentityConfig.cs in Model folder in TestLib and Startup in root of TestLib and change respective references in my web project.
I have removed OwinStartupAttribute from Startup.cs in web project and added OwinStartupAttribute to Startup.cs in TestLib.
And all seems to be working well also code first, but here I have some questions whether I am doing things correctly or not.
1) Is it OK to have Startup.cs in class library?
2) At now I have other models for my database in "ApplicationDbContext"
class, which creates table correctly in database.
So
1.Is it OK to use ApplicationDbContext instead of my CustomContext & can I
use this class library with my other application like some
windows application which do not use identity? OR
Should I keep separate context? OR
Is it possible to remove ApplicationDbContext and use my CustomContext?

Hosting an asp.net and a web api my self

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

Asp.net api dependency injection location

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.

Is it possible for ASP.NET MVC website (not project) to return HttpResponseMessage

I am creating a RESTful webservice using ASP.NET MVC (not ASP.NET Web API). What I want to do is have every method in the controller return their result based on an input parameter (i.e. json or xml).
If I were using ASP.NET Web API, the HttpResponseMessage works for this purpose. When I attempt to return an HttpResponseMessage from a controller in ASP.NET MVC, there is no detail.
I have read that in this approach, I am supposed to use ActionResult. If I do this, then I need to create an XmlResult that inherits from ActionResult since it is not supported.
My question is why HttpResponseMessage does not work the same in both situations. I understand that in Web API, we inherit from ApiController and in ASP.NET MVC we inherit from System.Web.Mvc.Controller.
Any help is greatly appreciated.
Thanks,
EDIT 1
Much thanks to Fals for his input. My problem was in how to create an empty website and add all of the necessary functionality in. The solution was to use Nuget to get the packages mentioned in the comments and then to follow the steps in How to integrate asp.net mvc to Web Site Project.
Web Api is a Framework to develop Restfull services, based on HTTP. This framework was separeted into another assembly System.Web.Http, so you can host it everywhere, not only in IIS. Web API works directly with HTTP Request / Response, then every controller inherit from IHttpController.
Getting Started with ASP.NET Web API
MVC has It's implementation on System.Web.Mvc. coupled with the ASP.NET Framework, then you must use It inside an Web Application. Every MVC controller inherits from IController that makes an abstraction layer between you and the real HttpRequest.
You can still access the request using HttpContext.Response directly in your MVC controller, or as you said, inheriting a new ActionResult to do the job, for example:
public class NotFoundActionResult : ActionResult
{
private string _viewName;
public NotFoundActionResult()
{
}
public NotFoundActionResult(string viewName)
{
_viewName = viewName;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 404;
context.HttpContext.Response.TrySkipIisCustomErrors = true;
new ViewResult { ViewName = string.IsNullOrEmpty(_viewName) ? "Error" : _viewName}.ExecuteResult(context);
}
}
This ActionResult has the meaning of respond thought HTTP Error.
As a matter of fact, it is indeed possible. You basically have two options:
develop your custom ActionResult types, which can be an heavy-lifting work and also quite hard to mantain.
add WebAPI support to your website.
I suggest you to do the latter, so you will have the best of two worlds. To do that, you should do the following:
Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
Add one or more ApiControllers to your /Controllers/ folder.
Add a WebApiConfig.cs file to your /App_Config/ folder where you can define your Web API routing scheme and also register that class within Global.asax.cs (or Startup.cs) file.
The whole procedure is fully explained here: the various steps, together with their pros-cons and various alternatives you can take depending on your specific scenario, are documented in this post on my blog.

Categories

Resources