SignalR without OWIN - asp.net-mvc

I'm participating in the ASP MVC project.
I want to use SignalR in the project but I don't want to use OWIN lib.
As I understand, SignalR is registered in the application using this piece of code:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
How can I modify this to remove the dependency to OWIN?
I would like to use approach similar to RouteConfig.RegisterRoutes(RouteTable.Routes);

If you don't want the owin lib you can use SignalR 1.x.
protected void Application_Start()
{
RouteTable.Routes.MapHubs();
}

First be sure to Get-Package within the Package Manager Console and remove all previous installments Uninstall-Package [Id] -RemoveDependencies as this should give you a clean slate.
What worked for me without assembly nor dependency issues was using NuGet to install Microsoft.AspNet.SignalR Version 1.1.4 into your App and DataAccess. Then add the following to your Global.asax file:
// Add this Library for MapHubs extension
using System.Web.Routing;
protected void Application_Start()
{
// This registers the default hubs route: ~signalr
// Simply add the line below WITHIN this function
RouteTable.Routes.MapHubs();
}
[Did this using Visual Studios 2015 Enterprise on 10/29/2015]

I was able to do it following this Microsoft documentation: https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.1
Their sample startup class is located here: https://github.com/aspnet/AspNetCore.Docs/blob/master/aspnetcore/signalr/hubs/sample/Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// other configure code
// ...
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// other configure code
// ...
app.UseSignalR(route =>
{
route.MapHub<ChatHub>("/chathub");
});
}

Related

How to register OData extension methods in .NetCore 3.1 outside of UseMvc middleware

After migrating my API from .net core 2.2 to 3.1, I am facing some issues to decide which is the best approach I should follow to register OData extension methods for my API. Currently, I have this code
public void ConfigureServices(IServiceCollection services)
{
....
#region OData
services.AddOData();
#endregion
....
}
On the Configure method
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
...
app.UseAuthentication();
app.UseMvc(routeBuilder =>
{
routeBuilder.Select().OrderBy().Filter().MaxTop(1000).Count();
routeBuilder.EnableDependencyInjection();
});
...
}
How can I register Select() OrderBy() Filter() .... using the following approach? Is this the right way to do it, without registering UseMvc?
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
...
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
...
}
Check this article out: Experimenting with OData in ASP.NET Core 3.1.
Apparently .NET Core 3.0 and 3.1 don't support OData yet. You can, however, use the beta version, the steps for which is explained in the article.
Update:
They do support OData as of version 7.3.0. However, they cannot be used with endpoint routing yet. You can follow this Github thread for updates, in particular, this answer

gRPC and MVC in same ASP.NET Core 3.0 Application

I am building out small, single purpose micro-services that require access via gRPC and Rest. We are implementing on ASP.NET Core 3.0. I realize this is pretty fresh stuff and have been looking for some reasonably complete reference implementations that demonstrate how to get this done.
I have a small .NET Service (Business Logic) call it IOrders. Now I want to wire up both gRPC and MVC (HTTP) against this back end service.
Any examples, github repos, blogs to follow or look around in would be greatly appreciated.
I had exactly same issue. I am runing.NET Core 3.0 and Grpc.AspNetCore Version 2.23.1. The biggest problem was to start it without SSL (not recommended for prod environments). Using certificate i found this github Secure_gRpc to be nice example.
Running without ssl for dev environments could be achieved in this way.
Program.cs file. Key aspects is to set HttpProtocols.Http1AndHttp2. I also removed certificate just to get it running. Uncomment next line to use SSL and certificate
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.ConfigureKestrel(options =>
{
options.Limits.MinRequestBodyDataRate = null;
options.ListenLocalhost(8008, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
listenOptions.UseHttps(adapterOptions =>
{
adapterOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate;
adapterOptions.ServerCertificate = null;
});
//listenOptions.UseHttps("<path to .pfx file>", "<certificate password>");
});
});
});
}
Startup.cs is pretty straightforward. It is very important to remember if you modify Startup.cs file order of added services is very important. If it doesnt work try other order and/or find official documentation.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc((options => { options.EnableDetailedErrors = true; }));
services.AddMvc(options => options.EnableEndpointRouting = false);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
});
}
}

Asp.net 5 web api dependency resolver

I have created project with an asp.net 5 web api template. The startup.cs file content is like this.
public class Startup
{
public Startup(IHostingEnvironment env)
{
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseMvc();
}
}
I want to use a IoC framework like Autofac, StructureMap and Ninject. But How can I change default web api dependency resolver with a framework?
For example StructureMap container is set like this:
var container = new StructureMap.Container(m=>m.Scan(x =>
{
x.TheCallingAssembly();
x.WithDefaultConventions();
}));
But can not set it in web api life.
Check out the StructureMap.Dnx project:
https://github.com/structuremap/structuremap.dnx
Usage
The package contains a single, public extension method, Populate.
It's used to populate a StructureMap container using a set of ServiceDescriptors or an IServiceCollection.
Example
using System;
using Microsoft.Extensions.DependencyInjection;
using StructureMap;
public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddWhatever();
var container = new Container();
// You can populate the container instance in one of two ways:
// 1. Use StructureMap's `Configure` method and call
// `Populate` on the `ConfigurationExpression`.
container.Configure(config =>
{
// Register stuff in container, using the StructureMap APIs...
config.Populate(services);
});
// 2. Call `Populate` directly on the container instance.
// This will internally do a call to `Configure`.
// Register stuff in container, using the StructureMap APIs...
// Here we populate the container using the service collection.
// This will register all services from the collection
// into the container with the appropriate lifetime.
container.Populate(services);
// Finally, make sure we return an IServiceProvider. This makes
// DNX use the StructureMap container to resolve its services.
return container.GetInstance<IServiceProvider>();
}
}
Documentation here might help:
http://docs.asp.net/en/latest/fundamentals/dependency-injection.html#replacing-the-default-services-container

After install owin package to my vs2012 i cant found my create owin startup class

I have installed Microsoft Owin package to my VS2012 but while creating a new class i could not see my owin start up class for creating a new class.
It should be created by the SignalR package I think?
[assembly: OwinStartup(typeof(SignalRConfig))]
namespace MyApp.App_Start
{
public static class SignalRConfig
{
public static void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

I wish to add an ASP.NET Web API to an ASP.NET MVC 4 Web Application project, developed in Visual Studio 2012. Which steps must I perform to add a functioning Web API to the project? I'm aware that I need a controller deriving from ApiController, but that's about all I know.
Let me know if I need to provide more details.
The steps I needed to perform were:
Add reference to System.Web.Http.WebHost.
Add App_Start\WebApiConfig.cs (see code snippet below).
Import namespace System.Web.Http in Global.asax.cs.
Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
Add a controller deriving from System.Web.Http.ApiController.
I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.
App_Start\WebApiConfig.cs:
using System.Web.Http;
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
Global.asax.cs:
using System.Web.Http;
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Update 10.16.2015:
Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.
To add WebAPI in my MVC 5 project.
Open NuGet Package manager console and run
PM> Install-Package Microsoft.AspNet.WebApi
Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already
Right click controllers folder > add new item > web > Add Web API controller
Web.config will be modified accordingly by VS
Add Application_Start method if not there already
protected void Application_Start()
{
//this should be line #1 in this method
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Add the following class (I added in global.asax.cs file)
public static 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 }
);
}
}
Modify web api method accordingly
namespace <Your.NameSpace.Here>
{
public class VSController : ApiController
{
// GET api/<controller> : url to use => api/vs
public string Get()
{
return "Hi from web api controller";
}
// GET api/<controller>/5 : url to use => api/vs/5
public string Get(int id)
{
return (id + 1).ToString();
}
}
}
Rebuild and test
Build a simple html page
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../<path_to_jquery>/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var uri = '/api/vs';
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
alert('got: ' + data);
});
$.ajax({
url: '/api/vs/5',
async: true,
success: function (data) {
alert('seccess1');
var res = parseInt(data);
alert('got res=' + res);
}
});
});
</script>
</head>
<body>
....
</body>
</html>
UPDATE 11/22/2013 - this is the latest WebApi package:
Install-Package Microsoft.AspNet.WebApi
Original answer (this is an older WebApi package)
Install-Package AspNetWebApi
More details.
As soon as you add a "WebApi Controller" under controllers folder, Visual Studio takes care of dependencies automatically;
Visual Studio has added the full set of dependencies for ASP.NET Web
API 2 to project 'MyTestProject'.
The Global.asax.cs file in the project may require additional changes
to enable ASP.NET Web API.
Add the following namespace references:
using System.Web.Http;
using System.Web.Routing;
If the code does not already define an Application_Start method, add the following method:
protected void Application_Start()
{
}
Add the following lines to the beginning of the Application_Start method:
GlobalConfiguration.Configure(WebApiConfig.Register);
You can install from nuget as the the below image:
Or, run the below command line on Package Manager Console:
Install-Package Microsoft.AspNet.WebApi
Before you start merging MVC and Web API projects I would suggest to read about cons and pros to separate these as different projects. One very important thing (my own) is authentication systems, which is totally different.
IF you need to use authenticated requests on both MVC and Web API, you need to remember that Web API is RESTful (don't need to keep session, simple HTTP requests, etc.), but MVC is not.
To look on the differences of implementations simply create 2 different projects in Visual Studio 2013 from Templates: one for MVC and one for Web API (don't forget to turn On "Individual Authentication" during creation). You will see a lot of difference in AuthencationControllers.
So, be aware.
NOTE : this is just an abbreviation of this answer above
Open NuGet Package manager console and run
PM> Install-Package Microsoft.AspNet.WebApi
Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already
Add the following class
public static 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 }
);
}
}
Add Application_Start method if not there already (in global.asax.cs file)
protected void Application_Start()
{
//this should be line #1 in this method
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Right click controllers folder > add new item > web > Add Web API controller
namespace <Your.NameSpace.Here>
{
public class VSController : ApiController
{
// GET api/<controller> : url to use => api/vs
public string Get()
{
return "Hi from web api controller";
}
}
}
The above solution works perfectly. I prefer to choose Web API option while selecting the project template as shown in the picture below
Note: The solution works with Visual Studio 2013 or higher. The original question was asked in 2012 and it is 2016, therefore adding a solution Visual Studio 2013 or higher.
I had same problem, the solution was so easy
Right click on solotion
install Microsoft.ASP.NET.WebApi from "Manage Nuget Package for Sulotion"
boom that's it ;)

Resources