Swagger and ServiceStack 4.0 - c#

First, I'll ask my question, then explain our problems found during testing. We can't seem to access the Swagger API on the resources route using ServiceStack 4.0. Is this still supported?
We're starting a greenfield project and are investigating ServiceStack. As recommended, we're using version 4.0 from http://ServiceStack.net. We've established a "Security" service and verified that /Security/User/username correctly returns our information about the user. End to end tests of ServiceStack are working great.
As we go forward, we also want to document our API using Swagger. It appears in our tests that the resources route is no longer supported, or at least is not working, in version 4.0. We've downloaded all the sample projects for guidance and they're all using ServiceStack 3.9.33, so not much luck using the samples. We've tried these local URLs for the Swagger resources snapshot:
localhost:85/resources
localhost:85/api/resources (with routing changes in the web.config
localhost:85/security/resources
localhost:85/api/security/resources (with routing changes in the web.config)
All with no luck. What are we missing?
Here is our AppHost class:
public class AppHost : AppHostBase
{
public AppHost()
: base("API Services", typeof(SecurityService).Assembly)
{
}
public override void Configure(Container container)
{
Plugins.Add(new SwaggerFeature());
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(UserValidator).Assembly);
}
}
And the relevant code from our Global.asax file:
protected void Application_Start(object sender, EventArgs e)
{
new AppHost().Init();
}
We've got the lastest of all packages using NuGet and Visual Studio 2013. Any guidance for ServiceStack newbies is appreciated.

I wish the solution were smarter than this, if only so that I felt that I understood the problem, but removing and then reinstalling all ServiceStack packages via the package management console solved the issue. Thanks to all who helped me to debug.

Related

Could not load file or assembly 'System.Web.Mvc, Version=4.0.0.0...' with Google Apis

i've seen all the other posts about the System.Web.Mvc problem, and i tried all the solutions. But nothing seems to be working so far.
I have a pretty big project, which already has a lot of references to lots of nuget packages.
Now i'm trying to add Google.Apis.Auth.Mvc to authenticate with google (and then access some sheets with that).
it works fine and i can build the project fine, until i start following the step Web applications (ASP.NET MVC) with the code here https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth
i tried it with a simple class:
public class foo : FlowMetadata
{
public override IAuthorizationCodeFlow Flow => throw new NotImplementedException();
public override string GetUserId(Controller controller)
{
throw new NotImplementedException();
}
}
but then i start getting the following error
then i tried all the solutions i could find on the topic, but nothing's working so far.
the weird part is, when i update the nuget system.web.mvc from 5.2.3 to 5.2.7, then it's complaining about a different version:
in the output, the log is talking about retrieving the loaderException.
Problem is, it's not even building, so how could i debug anything.
I tried debugging vs with another vs instance, but it doesn't stop for any exception.
anyway, i have no more ideas to try and would appreciate if anyone can help.
thx

Where do I register IMemoryCache in my ASP.NET application?

I have an ASP.NET web application that I created from Visual Studio 2015 Community Edition. The .NET Framework is 4.6.1.
I have no idea which version of ASP.NET my web application is using ASP.NET MVC 4? ASP.NET MVC 5? It's not mentioned anywhere.
I'm trying to register IMemoryCache service (from Microsoft.Extensions.Caching.Memory) into my Microsoft Unity container. However, anything I found about it on Google refers to adding services.AddCaching() in a Startup.cs file.
I don't have a Startup.cs file. I only see Global.asax. Furthermor, all my custom dependencies are registered within UnityConfig.cs which was provided when installing the NuGet package Unity.Mvc which is a Microsoft Unity bootstrapper for ASP.NET by Microsoft.
Any help appreciated.
Edit:
Here's a screenshot of my project:
In .NET Core AddMemoryCache Extensions looks like this:
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
So in .Net Framework you can use something like this (for Autofac):
builder.RegisterType<MemoryCache>().As<IMemoryCache>().SingleInstance();
UPD: However MemoryCachedependends on IOptions<> you should register it too:
builder.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptions<>)).SingleInstance();
builder.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptionsSnapshot<>)).InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(OptionsMonitor<>)).As(typeof(IOptionsMonitor<>)).SingleInstance();
builder.RegisterGeneric(typeof(OptionsFactory<>)).As(typeof(IOptionsFactory<>));
builder.RegisterGeneric(typeof(OptionsCache<>)).As(typeof(IOptionsMonitorCache<>)).SingleInstance();
The things you are referring to are part of the ASP.Net Core (ASP.Net 5)
In the new version you no longer have a Global.asax file, you have a new Startup processed defined in a Startup class. Also, DI is standard, so things work in a different way now. So either upgrade to the latest version of ASP.Net or apply use the DI solutions for the older version:
RESOLVING DEPENDENCIES IN ASP.NET MVC 5 USING UNITY CONTAINER
Also the package you are using is for the new ASP.NET version.
Introduction to ASP.NET Core
If you are using Unity, you can do something similar like this
in UnityConfig.cs
var memoryCache = new MemoryCacheService(new MemoryCacheOptions());
container.RegisterInstance<IMemoryCache>(memoryCache);
create your MemoryCacheService
public class MemoryCacheService : MemoryCache
{
public MemoryCacheService(IOptions<MemoryCacheOptions> optionsAccessor) : base(optionsAccessor)
{
}
}
yourcontroller
private readonly IMemoryCache _memoryCacheService;
public yourcontroller(IMemoryCache memoryCacheService)
{
_memoryCacheService = memoryCacheService;
}
public IHttpActionResult AddCacheItem(string cacheKey)
{
_memoryCacheService.Set(cacheKey, DateTime.Now.Ticks );
var temp = _memoryCacheService.Get(cacheKey);
return Ok(temp);
}
I am also facing a problem with IMemoryCache. I have framework version 4.5.2. try the below step.
First, install below NuGet packages for .net framework 4.5.2 and MVC
Microsoft.Extensions.Caching.Abstractions --version 1.1.2
Microsoft.Extensions.Caching.Memory --version 1.1.2
After installing those packages please below the line in the AutofacConfig file
In .Net Framework you can use something like this (for Autofac):
builder.RegisterType<MemoryCache>().As<IMemoryCache>().SingleInstance();
However MemoryCachedependends on IOptions<> you should register it too:
builder.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptions<>)).SingleInstance();
Please go through the below link, which i think will help you.
Setting Up the Unity Container

Ninject & WebAPI: Getting started after install from NuGet

I installed the NuGet package Ninject Integration for WebApi2 via the Package Manager Console.
According to the wiki on the project's GitHub pages, this should have created a class called NinjectWebCommon in the App_Start folder. But it didn't.
That same GitHub wiki page explains what you should see so that you can add it yourself. So I tried creating the NinjectWebCommon class myself. The problem here is that I can't find the namespace for OnePerRequestModule in the following snippet.
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
The alternative, and according to that GitHub wiki page there's no effective difference between the two, is to modify the global.asax. So I tried this method and added some bindings like so
private void RegisterServices(IKernel kernel)
{
kernel.Bind<IEntityAccess>().To<EntityAccess>();
kernel.Bind<IDictionaryRepository>().To<DictionaryRepository>();
}
and found that my project builds, but when a request is sent to the WebAPI project it can't be found (i.e., I receive a 404 response).
So there's obviously some other piece of necessary wiring up which isn't in my project.
It appears that despite changing my global.asax to derive from NinjectHttpApplication, the global.asax is no longer being called.
Can anyone tell me what I might be missing? I've uninstalled and reinstalled the NuGet package a few times but the NinjectWebCommon class never appears, nor does my global.asax file ever get modified.
I've also read Ninject's own documentation but frustratingly this is a fairly large tutorial covering the basics of IoC and how Ninject operates rather than telling you how to get started with using Ninject.
There's also this SO post asking how to get started with Ninject for WebAPI, so it looks like something's amiss with their NuGet package.
And like that, I've just found the answer: there is an additional NuGet package which must be referenced:
Ninject.Web.WebApi.WebHost
Installing "Ninject integration for WebApi2" package is not sufficient.
This really should be more clearly explained.

Can't find Request.GetOwinContext

I have been searching for an hour trying to figure out why this isn't working.
I have a ASP.Net MVC 5 application with a WebAPI. I am trying to get Request.GetOwinContext().Authentication, however I can't seem to find how to include GetOwinContext. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TaskPro.Models;
namespace TaskPro.Controllers.api
{
public class AccountController : ApiController
{
[HttpPost]
[AllowAnonymous]
public ReturnStatus Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var ctx = Request.GetOwinContext(); // <-- Can't find this
return ReturnStatus.ReturnStatusSuccess();
}
return base.ReturnStatusErrorsFromModelState(ModelState);
}
}
}
From what I've read, it should be part of the System.Net.Http, but I've included that and it still isn't resolving. Ctrl-Space doesn't give me any intellisense options either.
What am I missing here?
The GetOwinContext extension method is in the System.Web.Http.Owin dll which needs to be downloaded as a nuget package (The nuget package name is Microsoft.AspNet.WebApi.Owin)
Install-Package Microsoft.AspNet.WebApi.Owin
See msdn here: http://msdn.microsoft.com/en-us/library/system.net.http.owinhttprequestmessageextensions.getowincontext(v=vs.118).aspx
Nuget package here: https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Owin
However, the method is still part of the System.Net.Http namespace, so the using definitions you have should be fine.
EDIT
Okay, to clear up some confusion: If you are using an ApiController (i.e MyController : ApiController) you will require the Microsoft.AspNet.WebApi.Owin package.
If you are using a regular Mvc controller (i.e. MyController : Controller) you will need the Microsoft.Owin.Host.SystemWeb package.
In MVC 5 the pipelines for Api and regular MVC were very different, but often have the same naming conventions. So an extension method in one does not apply to the other. Same for a lot of the action filters etc.
None of these worked for me. I had to compare Nuget packages with one that was created with Identity and I found this Nuget package missing which when added fixed the issue for me
Microsoft.Owin.Host.SystemWeb
Apparently you need it to run OWIN on IIS using the ASP.NET request pipeline (read you're screwed without it!)
In WEB API, you can get the reference using the following:
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
it works in Identity 2.0
You may need to add the NuGet package Microsoft.Owin.Host.SystemWeb in order to do this:
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
In my case I need to add
using Microsoft.AspNet.Identity.Owin;
for resolving GetOwinContext and then GetUserManager in following line.
Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
I have this problem and I download extra package from nuget to solve my problem,(run following command in Package Manager Console)
Install-Package Microsoft.Owin.Host.SystemWeb
(Please note that this answer is for ASP.NET Web API which corresponds to the tag used on the question. See this question if your inquiry is with respect to ASP.NET MVC.)
The question does not specify how the ASP.NET Web API service is to be hosted. The dialog in this post indicates (emphasis mine):
kichalla wrote Oct 24, 2014 at 1:35 AM
If you are NOT self-hosting, do not use Microsoft.AspNet.WebApi.Owin
package with IIS...this package is only supposed to be used with self
hosting.
Use of the Microsoft.AspNet.WebApi.Owin package is recommended in the accepted answer. In this answer I am reporting what has worked for me when hosting an ASP.NET Web API service in IIS.
First, install the following NuGet package:
Microsoft.Owin.Host.SystemWeb
OWIN server that enables OWIN-based applications to run on IIS using
the ASP.NET request pipeline.
(Note that as I write, the latest available version of this NuGet package is 3.1.0. Also, to the extent that it might matter, I am using Visual Studio 2013 Update 5.)
After installing this NuGet package, you can do the following:
using Microsoft.Owin;
using System.Web;
IOwinContext context = HttpContext.Current.GetOwinContext();
// or
IOwinContext context = HttpContext.Current.Request.GetOwinContext();
Now, to shed some light on how these statements are resolved. In Visual Studio, if you right-click GetOwinContext in either statement and select "Peek Definition," Visual Studio will display the following:
// Assembly Microsoft.Owin.Host.SystemWeb.dll, v3.1.0.0
using Microsoft.Owin;
using System;
using System.Runtime.CompilerServices;
namespace System.Web
{
public static class HttpContextExtensions
{
public static IOwinContext GetOwinContext(this HttpContext context);
public static IOwinContext GetOwinContext(this HttpRequest request);
}
}
As you can see, within the System.Web namespace, there are two GetOwinContext extension methods:
One on the HttpContext class, and
The other on the HttpRequest class.
Again, for those hosting their Web API service in IIS, my hope is that this clears up any ambiguity regarding where a definition for GetOwinContext can be found with respect to this late date in 2017.
This took me forever to find a simple answer: but what I did was use the Get extension of the single instance of the IOwinContext that was instantiated in the startup. So it came out like this:
private readonly IOwinContext _iOwinContext = HttpContext.Current.GetOwinContext();
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? _iOwinContext.Get<ApplicationUserManager>() ;
}
private set
{
_userManager = value;
}
}
The GetOwinContext() extension method is not found in threads other than the GUI thread.
So be careful to not call this function from within any awaited function.
After looking at the ASP.NET default project I discovered I needed to include this in my application startup:
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in
// with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);`
I was missing package: Microsoft.AspNet.WebApi.Owin for ApiControllers.
Hope this helps!
I had this same problem and solved it by using a private method:
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
This worked swimmingly for me.
I had to add package Microsoft.AspNet.Identity.Owin

Ninject and asp.net MVC4

I have a MVC3 application that I would like to port to MVC4. I am using Ninject for dependency injection. Using Nuget, I added "Ninject" to my project and created a controller factory as shown below
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
//Add ninject bindings here
}
}
This works fine for MVC3 but things have changed in MVC4. I did some digging and found this link that explains how to get ninject working for MVC4
http://haacked.com/archive/2012/03/11/itrsquos-the-little-things-about-asp-net-mvc-4.aspx
However, I am having trouble getting the code in the above link to compile. Specifically, The code that I am supposed to place in the Start() method of the web.common file gives me unresolved namespace errors
GlobalConfiguration.Configuration.ServiceResolver
.SetResolver(DependencyResolver.Current.ToServiceResolver());
Both "ServiceResolver" and ".SetResolver" are unresolved. What references do I need to add to enable these? Also, if possible can you point me towards a tutorial showing me how to get ninject working in MVC4 without having to install the nuget package ninject.mvc3? I ask because I would prefer not to have any packages installed in my application that were written for MVC3 specifically to avoid things from breaking down the line if these nuget packages are updated.
edit: I should have added that I am using Visual studio 2012 and .Net 4.5
Phil's article is about using Ninject with WebAPI. Is that what you mean? You don't need to do that for normal MVC injection. Also, you should be using the Ninject.MVC3 NuGet package with MVC4 (yes, I know it says MVC3, but it still works fine because NuGet sets up Assembly Version Redirects that make everything Just Work), this sets everything up and you don't need a controller factory. Just edit the NinjectWebCommon.cs file to add your bindings.
Just simply Add namespace
Using Ninject;
after installing template from Nuget...
U just install "Ninject" but not "Ninject for MVC3" from Nuget Template

Categories

Resources