Start asp.net WebApi project from WPF project within solution using OWIN - c#

I have a .NET solution which has two projects:
WPF project for the WPF application
ASP.NET WebApi project with a few controllers
I want to host the WebApi inside my WPF application (using OWIN). Any idea how can I do this?
If I create my controllers in the WPF project itself then I can host them using WebApp.Start (and pass a config class).

Here's an example of how to make a desktop application with OWIN and WebApi http://www.codeproject.com/Articles/869223/ASP-NET-Web-Api-Create-a-Self-Hosted-OWIN-Based-We
It's true that it's a console based application but you could use that in the bootstrap of your application to start the OWIN server when the app starts.
I would also advise trying it in a new test project until you get a hang of it before starting to create api controllers and mapping out routes

Yeah. Start reading documentation. Then "just go". This (self-hosting) is exactly what OWIN was designed to do and it is all documented.
IN your app at one point you will configure and start an OWIN based server. Contrary to how you do normal web apps, you can abandon the WebApi project - all controllers etc. can live in an assembly. Reflection is used to find them.

Related

Azure Function App & Web API in same solution

I need a both a Web API project and a function app project which share the same services / class libraries etc. A few questions
Is it bad practice to place them both in the same solution (or should they be in seperate repositories
Should the services be registered in the Startup class of the Web Api or the function app, or a mixture of the 2? Is it okay to register services only used by the function app in the web api startup class as this would make life easier? The services will do similar things and in some cases the same services will be used by both.
I am likely to only require a few timer trigger functions, most of the application will be build on the web api.
Specifically, the rest API will serve a frontend UI and the function app will provide updates to products on timer triggers.
Thanks for any guidance in advance and apologise if these are silly questions!
For #1 - I think it's totally fine to have them both in the same (git) repository - you might be following a monorepo strategy, OR these projects might be closely related e.g. part of the same business domain/capability where you might have something like a a core Web API project (ASP.NET Core WebApi) as well as some Function App event handlers (in a Function App project) that respond to external async events and invoke the core Web API. Alternatively, if they're completely unrelated repos and you're not following a monorepo strategy then maybe they should be in separate repos.
For #2 - some services might be exclusive to the ASP.NET Core WebApi, some exclusive to the Function App, and some might be shared. Assuming all the code is in the same repo; for the shared dependencies, you might consider having a third 'class library' project in the same git repo that can be referenced by both the ASP.NET Core WebApi project as well as the Function app project. This 'class library' project could contain all the shared dependencies. Dependencies should be registered in the startup of both the Web Api AND the function app.

Can I add ASP.NET Core MVC to existing ASP.NET Web Forms Application

I have our legacy ASP.NET web forms application. I need to create new pages and I want to use the APS.NET Core MVC project for those new pages. Is this possible? How It can be done?
Just to add, I don't need to keep the state b/w pages from both projects.
I tried to create a separate MVC core project (under the same solution) but can't figure out how to do the routing between them.
Edit: I know this is possible by using MVC .NET Framework. My question is specific to MVC Core.
No, you can not. While the objects used by the request pipeline seem very similar between the Asp.Net and Asp.Net Core, they are in fact totally different objects which come from totally different namespaces. The two are totally different pipelines that don't interact in any way. So at the end of the day it's either going to be one pipeline listening for incoming web requests or it's gonna be the other. You can't have both trying to process the web request for your web application.
By way of contrast, in the Asp.Net when using the Full framework you can have Web Forms and MVC both coexist no problem. This is because both use the same request pipeline that lives in the System.Web namespace. So while the way they respond to the request might be a bit different, they both use the same HttpContext object. This is not true of Asp.Net Core. It uses a totally different HttpContext object located in the Microsoft.AspNetCore.Http namespace.
You may also find my answer for this question informative: Is it at all possible to migrate ASP.NET ASPX solution to ASP.NET Core 2.0?

use owin to self host web api

I'm self hosting web api using owin on client-server application based on MVC architecture. I see a lot of code examples that shows that the Startup class with the configuration, and the Program class with the Main method that start the owin self host "using (WebApp.Start(url: baseAddress))" - are at the same project. Should I desperate owin self host to one project so the WebApp.Start will be in one project, and web api with Startup claas to another one, with all the controllers and so?
The common answer is that it depends. Usually self host applications is very simple to provide some simple functionality. In that case since both parts are simple there is no need to separate them (host code and Asp.Net Mvc) and they can be placed in one project as an application layer. But if you are trying to add some complexity to host code (e.g. some warm up of Asp.Net Mvc app), then may be you should split your host code and Asp.Net Mvc app code in to two projects.
Found that it might be good idea inspired by separation of concerns: the self host should not know about the server and the opposite. Owin and web api have different job so they need to be separated.

c# Console App With Web API In vNext

i have a console application that contains a number of events that i want to hook into. I want to build it into a microservice and have an umber of smaller console based applications that run continuously with an API that can configure the application or retrieve data. I have the Web API and application completely written. However im stuck in marrying the two together, i did think about doing it the Dependency Injection way with .AddTransient however i cant seem to add events to it.
does anyone know of a way in which i can have my console application running continuously (its a DHCP service) and then re-configure it via an API and for it to update the application from the API controller.
everything is written in vNEXT using .NET Core.
Any help/pointers would be very much appreciated!
Make sure the console applications are created from the "Console Application (Package)" template. Add project references from the Web API to these console application projects. In the ConfigureServices of the Startup class of the Web API project you van add the class (which has the events) to the services collection (be careful with Transient though). I've worked out an example: https://github.com/DannyvanderKraan/InjectDependencyWithEvents
Does this help?

Web API in MVC solution in separate project

I am creating a new MVC4 project, and research has lead me to believe that communicating from javascript to the server side is better achieved now through web API framework rather than controller actions. Is my understanding correct on this?
I am presuming that I can share all my attributes etc between web API and MVC controllers so on the face it, it does not seem a massive change for me.
When I am setting up applications, I like to split components out in to projects. My plan was to have a MVC project and a web API project. But I have ran in to issues. For example I have ended up with 2 apps as such, separate routing set up etc etc.
So my question is, in a MVC application should the web API framework sit within the same project, or should the web API be separated into a project of its own and work around the issues?
Unfortunately you are wrong about that - I am presuming that I can share all my attributes etc between web api and mvc controllers so on the face it, it does not seem a massive change for me.
Many of the concepts used by Web API and MVC, even though similar at first glance, are actually not compatible. For example, Web API attributes are System.Web.Http.Filters.Filter and MVC attributes are System.Web.Mvc.Filter - and they are not interchangeable.
Same applies to many other concepts - model binding (completely different mechanisms), routes (Web API uses HTTPRoutes not Routes, even though they both operate on the same underlying RouteTable), dependency resolver (not compatible) and more - even though similar on the surface, are very different in practice. Moreover, Web API does not have a concept of areas.
Ultimately, if all you are trying to do achieve is to have a "new, trendy" way of serving up JSON content - think twice before going down that path. I certainly wouldn't recommend refactoring any existing code unless you are really looking into embracing HTTP and building your app in a RESTful way.
It all really depends on what you are building. If you are starting a new project, and all you need is to serve up some JSON to facilitate your web app - provided you willing to live with some potentially duplicate code (like the stuff I mentioned above), Web API could easily be hosted within the same project as ASP.NET MVC.
I would only separate Web API into a separate project if you are going to build a proper API for your online service - perhaps to be consumed by external customers, or by various devices - such as fueling your mobile apps.
IMO, security and deployment should drive your decision. E.g., if your MVC app uses Forms authentication but you're interested in using Basic authentication (with SSL) for your API, separate projects are going to make your life easier. If you want to host yout site at www.example.com but host your API as api.example.com (vs. www.example.com/api), separate projects will make your life easier. If you separate your projects and subdomain them accordingly and you intend to leverage your own API from your MVC app, you will have to figure out how to deal with the Same Origin Policy issue for client-side calls to your API. Common solutions to this are to leverage jsonp or CORS (preferably if you can).
Update (3/26/2013): Official CORS support is coming: http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API
After some degree of experience (creating API for apps and for mvc). I mostly do both.
I create a separate project for api calls that come from other clients or other devices (Android/IOS apps). One of the reasons is because the authentication is different, it is token based (to keep it stateless). I do not want to mix this within my MVC application.
For my javascript/jquery api calls to my mvc application, I like to keep things simple so I include a web api inside my MVC application. I do not intend to have token based authentication with my javascript api calls, because hey, it's in the same application. I can just use [authorize] attribute on a API endpoint, when a user is not logged in, he will not get the data.
Furthermore, when dealing with shopping carts and you want to store a users shopping cart in a session (while not logged in), you need to have this in your API as well if you add/delete products via your javascript code. This will make your API stateful for sure, but will also reduce the complexity in your MVC-API.
Steven from SimpleInjector (IoC framework) advises two separate projects: What is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependencyResolver in WebAPI
I have recently done almost the same thing: I started with a new MVC 4 web application project choosing the Web API template in VS2012.
This will create a Web API hosted in the same application as MVC.
I wanted to move the ApiControllers into a separate class library project. This was fairly easy but the solution was a bit hidden.
In AssemblyInfo.cs of the MVC 4 project add similar line of code
[assembly: PreApplicationStartMethod(typeof(LibraryRegistrator), "Register")]
Now you need the class LibraryRegistrator (feel free to name it whatever)
public class LibraryRegistrator
{
public static void Register()
{
BuildManager.AddReferencedAssembly(Assembly.LoadFrom(HostingEnvironment.MapPath("~/bin/yourown.dll")));
}
}
In the MVC 4 project also add reference to the Api library.
Now you can add Api controllers to your own separate class library (yourown.dll).
Even if your project is so complex as to warrant two "front ends" then I would still only consider splitting out webapi into a separate project as a last resort. You will have deployment headaches and it would be difficult for a newbie to understand the structure of your solution. Not to mention routing issues.
I would aim to keep the system.web namespace isolated in the one "presentation layer". Despite the webapi not being presentational it is still part of the interface of your application. As long as you keep the logic in your domain and not your controllers you should not run into too many problems. Also, don't forget to make use of Areas.
In addition to setup the separate DLL for the Web.Api.
Just a Suggestion:
Create the Project
Nugget WebActivatorEx
Create a a class Method to be called upon app_start
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(API.AppWebActivator),"Start")]
[assembly:WebActivatorEx.ApplicationShutdownMethod(typeof(API.AppWebActivator), "Shutdown")]
Register a web.api routes inside the Start Method
public static void Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Reference the Project to the Web Project. to activate the Start Method.
Hope this helps.
I tried to split the API controllers into a new project. All I've done is to create a new library project, moved the controllers inside folder named API.
Then added the reference of the library project to the MVC project.
The webAPI configuration is left in the MVC project itself. It works fine.

Categories