Web API Help Pages always empty - asp.net-web-api

I've added Help pages Nuget package to create documentation for my Web API but it doesn't work for me, no API methods are shown.
I uncommented line :
config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
I checked box XML documentation file and set path to App_Data/XmlDocument.xml
I don't use Glimpse as many solutions here write about it.
I even installed nuget package for help pages with authorization but it doesn't help
What is wrong with this? If I start empty project than it is working fine, but this API is too big to start all over again.

In case you are using OWIN as middleware (just like me), you may be initializing a new HttpConfiguration inside it´s startup method. The problem is that the HelpController and the HelpPageConfig are using GlobalConfiguration.Configuration, which seems to be wrong. What helped me:
Step 1: make the startup HttpConfiguration a static field
[assembly: OwinStartup(typeof(MyProject.API.Startup))]
namespace MyProject.API
{
public class Startup
{
//new
public static HttpConfiguration HttpCfg;
//
public void Configuration(IAppBuilder app)
{
HttpCfg = new HttpConfiguration();
WebApiConfig.Register(HttpCfg);
app.UseWebApi(HttpCfg);
AreaRegistration.RegisterAllAreas();
}
}
}
Step 2: go to HelpPageAreaRegistration and edit the RegisterArea method like this
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"HelpPage_Default",
"Help/{action}/{apiId}",
new { controller = "Help", action = "Index", apiId = UrlParameter.Optional });
//old
//HelpPageConfig.Register(GlobalConfiguration.Configuration);
//new
HelpPageConfig.Register(Startup.HttpCfg);
}
Step 3: go to HelpController and edit the standard constructor like this
//old
//public HelpController() : this(GlobalConfiguration.Configuration){ }
//new
public HelpController() : this(Startup.HttpCfg){ }
I hope this helps and isn't too late ;)

Related

Issue with Simple Injector while using with Web API

I am having issue using Simple Injector with WebAPI project that gets created default with VS 2015.
I am having the AccountController having the below constructor
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
In order to register these I used the below code in Simple Injector
// Create the container.
var apiContainer = new Container();
apiContainer.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
apiContainer.Options.ConstructorResolutionBehavior = new ConstructorBehavior();
//register the classes that we are going to use for dependency injection
apiContainer.Register<IUserStore<ApplicationUser>>(() => new UserStore<ApplicationUser>(new ApplicationDbContext()),Lifestyle.Scoped);
apiContainer.Register<IDataProtector>(() => new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider().Create("ASP.NET Identity"),Lifestyle.Transient);
apiContainer.Register<ISecureDataFormat<AuthenticationTicket>, SecureDataFormat<AuthenticationTicket>>(Lifestyle.Transient);
apiContainer.Register<ITextEncoder, Base64UrlTextEncoder>(Lifestyle.Scoped);
apiContainer.Register<IDataSerializer<AuthenticationTicket>, TicketSerializer>(Lifestyle.Scoped);
//apiContainer.RegisterCommonClasses();
//register the webapi controller
apiContainer.RegisterWebApiControllers(configuration);
but after this I am getting the warning message that says
[Disposable Transient Component] ApplicationUserManager is registered as transient, but implements IDisposable.
Can someone Please help me with this how to resolve this ? With Default Web api project with VS 2015 it adds Account controller and that use ApplicationUserManager and has below details
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
Another issue I am getting as below
The constructor of type HttpConfiguration contains the parameter with name 'routes' and type HttpRouteCollection that is not registered. Please ensure HttpRouteCollection is registered, or change the constructor of HttpConfiguration.
This is with the HelpController as it uses the below details:
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
public HelpController(HttpConfiguration config)
{
Configuration = config;
}

MVC5 dependency injection issue

I have created an application using MVC5 with the onion architecture approach. The solution contains 3 projects (core, infrastructure, and UI). The UI contains both Web API controllers and MVC controllers. The issue I’m running into is dependency injection. I have installed Unity.MVC5 & Unity.WebApi. My UnityConfig.cs under App_Start Looks like this:
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<IPricingService, PricingService>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
My global.asax looks like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
UnityConfig.RegisterComponents();
}
To test out my controller, I defined my home controller like this:
private readonly IPricingService _pricingService;
public HomeController(IPricingService PricingService)
{
this._pricingService = PricingService;
}
When running home page I get
No parameterless constructor defined for this object.
Now, moving to another test scenario, I created a web api controller and looks like this:
private readonly IPricingService _pricingService;
public TestApiController(IPricingService PricingService)
{
this._pricingService = PricingService;
}
Testing the web api generates this error:
An error occurred when trying to create a controller of type 'TextApiController'. Make sure that the controller has a parameterless public constructor.","exceptionType":"System.InvalidOperationException"
Not sure what I'm missing. Please advise.
You are supposed to inject the Unity.WebApi.DependencyResolver into the WebApi configuration not in GlobalConfiguration.Configuration.DependencyResolver.
public static void Register(HttpConfiguration config)
{
var container = new UnityContainer();
container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
// Other Web API configuration not shown.
}
You also need to implement a child container in the BeginScope method as shown in this MSDN article.

WebApi controller

I try to integrate autofac for webapi and I am having problem to make it work.
My controller constructor signature is:
public class AController: ApiController
{
public AController(IComponentContext componentContext)
{}
}
In my global.asax file i have called the following code in Application_Start
protected void Application_Start()
{
var builder = new ContainerBuilder();
builder.RegisterApiControllers();
container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
When I try to run my application and to access my ressource "/api/A", the server returns an error 500 complaining about the fact the controller does not have a default constructor. I though that was the task of the AutofacWebApiDependencyResolver to inject the container in my case. How can I fix my issue ?
Thanks,
I have found my issue .
Update this line to
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
sort the issue out.

How do I use Universal Membership Provider, EF, and MiniProfiler together?

If I use the Universal Membership Provider and a seperate database, Entity Framework and enable Mini Profiler for EF 4.2. I get error {"There is already an object named 'Applications' in the database."} when I first hit a line checking user credentials in my home view.
If I turn remove MiniProfilerEF.Initialize(); then I stop getting the error.
Any ideas?
Can I stop profiling the defaultconnection?
I have been banging my head against this issue for awhile now. Did some more digging today and was able to get it working. Here is what I did. In MiniProfiler.cs I defined two methods as follows:
public static DbConnection GetConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["MyModelConnectionString"].ConnectionString;
var entityConnStr = new EntityConnectionStringBuilder(connectionString);
var realConnection = new SqlConnection(entityConnStr.ProviderConnectionString);
return realConnection;
}
public static IMyModelsInterface GetProfiledContext()
{
var connection = new MvcMiniProfiler.Data.EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
var context = connection.CreateObjectContext<MyModel>();
return context;
}
NOTE: These two methods probably shouldn't be defined in MinProfilerPackage, but this was my first past/hack to get it working.
Then call GetProfiledContext() and use the context returned whenever you want the queries profiled. I injected this profile context into my controller factory using Ninject. My call looks something like this:
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
private void AddBindings()
{
var context = MiniProfilerPackage.GetProfiledContext();
IUnitOfWork uow = new UnitOfWork(context);
ninjectKernel.Bind<IRepository>().To<GenericRepository>().WithConstructorArgument("paramUnitOfWork", uow);
// ... rest of the method
}
NinjectControllerFactory is my controller factory that gets set in Application_Start.
protected void Application_Start()
{
// Add in DI for controller and repo associations
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
// ... rest of the method
}

Examples of how to use NServiceBus with NServiceBus.Ninject-CI in ASP.NET MVC 3 solution

I would like to experiment with NServiceBus using ASP.NET MVC 3. I've got a solution with NServiceBus installed, plus NinjectMVC3 and NServiceBus.Ninject-CI. Trouble is, I have no idea how to setup NServiceBus stuff in the NinjectMVC3.cs file in App_Start.
Rather annoyingly I'm having trouble finding any examples of how to use NServiceBus.Ninject-CI (I hate it when people don't bother giving examples of how to use their stuff).
Can someone help me get started please?
Load a module like this into the kernel to provide access to the bus
public class NServiceBusModule : NinjectModule
{
public override void Load()
{
this.Bind<IBus>().ToConstant(this.CreateBus()).InSingletonScope();
}
private IBus CreateBus()
{
return NServiceBus.Configure.WithWeb()
.NinjectBuilder(this.Kernel)
... // put NServiceBus config here
.CreateBus()
.Start();
}
}
Read the NServiceBus documentation about how to configure NServiveBus:
http://docs.particular.net/nservicebus/containers/ninject
http://docs.particular.net/samples/web/asp-mvc-application/
Hopefully this will help someone. I had a lot of trouble finding sample code for getting ninject working within NServiceBus.
This code below works for me in place of the more common Castle version:
public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{
#region IWantCustomInitialization Members
public void Init()
{
Configure
.With()
.NinjectBuilder(CreateKernel())
.XmlSerializer()
.MsmqTransport();
SetLoggingLibrary.Log4Net(XmlConfigurator.Configure);
}
protected IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load<MyCustomNinjectModule>();
return kernel;
}
#endregion
}
with the ninject module being the usual format, ie:
public class MyCustomNinjectModule : NinjectModule
{
public override void Load()
{
Bind(typeof(ILogger<>)).To(typeof(Log4NetLogger<>));
...
}
}

Resources