HTTP Error 403.14 in ASP.NET5 MVC6 - asp.net-core-mvc

I am just exploring ASP.NET 5 MVC 6 web app with new Visual Studio Community 2015 RC. DotNet framework 4.6.
I've added reference Microsoft.AspNet.MVC (6.0.0-beta4) from nuget. Then created Models,Views & Controllers directory. Also added HomeController and a view.
Here is my Startup.cs-
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
}
Home Conctoller-
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
But while i try to run the project, browser shows
HTTP Error 403.14
A default document is not configured for the requested URL.
Do I need to do anything to configure?

Try-
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
}
}

Related

How to enable compression in aspnetboilerplate dynamic web api

I tried adding Microsoft.AspNetCore.ResponseCompression in Myproject.web.host
And configured this
public void ConfigureServices(IServiceCollection services)
{
//other configs...
services.AddResponseCompression();
//other configs...
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//other configs...
app.UseResponseCompression();
app.UseMvc();
}
it worked for swagger, but not for the generated dynamic web api
Try to use a tool such as F12 developer tools, Fiddler or Postman to check the Accept-Encoding setting in the request header and the response headers. Perhaps the Content-Encoding and Vary headers aren't present on the response.
To solve this issue, you could try to refer the following steps to set the compression provider:
create a BrotliCompressionProvider class:
public class BrotliCompressionProvider : ICompressionProvider
{
public string EncodingName => "br";
public bool SupportsFlush => true;
public Stream CreateStream(Stream outputStream) => new BrotliStream(outputStream, CompressionMode.Compress);
}
Change the configure service as below:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddResponseCompression(options => {
options.Providers.Add<BrotliCompressionProvider>();
options.EnableForHttps = true;
});
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//other configs...
app.UseResponseCompression();
app.UseMvc();
}

Configure Autofac DI container in ASP.NET CORE 3.1 Web API and consumer service from controller

I need to configure Autofac DI container in ASP.NET CORE 3.1 Web API application and call register class from the container in Web API controller. I install Autofac.Extensions.DependencyInjection (6.0.0) and try to register container in my Startup.cs class but I am not able to use service. Also, do I need to configure the container in ConfigureServices(IServiceCollection services) class? The debugger does not hit IoCConfigurator() class after hitting point builder.RegisterModule(new IoCConfigurator());
Program.cs
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup.cs
public class Startup
{
public IConfiguration Configuration { get; }
public ContainerBuilder containerBuilder { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
containerBuilder = new ContainerBuilder();
}
public void ConfigureServices(IServiceCollection services)
{
ServicesConfigurator.Configure(services, Configuration);
ConfigureIoC(services, containerBuilder);
}
public void ConfigureIoC(IServiceCollection services, ContainerBuilder builder)
{
builder.RegisterModule(new IoCConfigurator());
}
IoCConfigurator.cs
public class IoCConfigurator: Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<NotifyService>().As<INotificationService>();
builder.RegisterType<UsersService>().AsSelf();
}
}
INotification Interface & Class
public interface INotificationService
{
void notifyUsernameChanged(Users users);
}
public class NotifyService : INotificationService
{
public void notifyUsernameChanged(Users users)
{
string changedUsername = users.Username;
Console.WriteLine("Username has changed to ... ");
Console.WriteLine(changedUsername);
}
}
User & User Service Class
public class Users
{
public string Username { get; set; }
public Users(string username)
{
this.Username = username;
}
}
public class UsersService
{
private INotificationService _notificationService;
public UsersService(INotificationService notificationService)
{
this._notificationService = notificationService;
}
public void ChangeUsername(Users users, string newUsername)
{
users.Username = newUsername;
_notificationService.notifyUsernameChanged(users);
}
}
API Controller where I want to class the UserService Class and get reference from DI container
[Authorize]
[Route("txn/v1/[controller]/[action]")]
[ApiController]
public class DashboardController : ControllerBase
{
[HttpPost("{name}")]
public ActionResult<HelloMessage> GetMessage(string name)
{
// call container here...
var result = new HelloMessage()
{
GivenName = name,
ReturnMessage = "Dashboard# Hello, Welcome to Texanite Digital"
};
return result;
}
Here is how I set it up. From command line:
md autof
cd autof
dotnet new webapi
dotnet add package Autofac.Extensions.DependencyInjection
Then edit using VS or VSCode. Program.cs - as you had it:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Next in Startup.cs, forget about ConfigureIoC, just register the services you want/need:
public void ConfigureContainer(ContainerBuilder builder)
{
// Register your own things directly with Autofac, like:
//builder.RegisterModule();
builder.RegisterType<NotifyService>().As<INotificationService>();
}
Then in DashboardController.cs you need to "inject" the needed services from the constructor:
public class HelloMessage {
public string GivenName { get; set; }
public string ReturnMessage { get; set; }
}
//[Authorize] Easier without Auth - don't need
[Route("[controller]")]
[ApiController]
public class DashboardController : ControllerBase
{
private readonly INotificationService _notifyService;
public DashboardController(INotificationService notifyService)
{
_notifyService = notifyService;
}
//[HttpPost("{name}")] - easier to test Get
[HttpGet("{name}")]
public ActionResult<HelloMessage> GetMessage(string name)
{
// call container here...
_notifyService.notifyUsernameChanged(new Users(name));
var result = new HelloMessage()
{
GivenName = name,
ReturnMessage = $"Dashboard {name}, Welcome to Texanite Digital"
};
return result;
}
}
My Results:
With console output:
Your UserService was a little "out of the loop" but you can add an Interface for it and register with container and add it to injected services of the controller(s).
I could zip the whole thing up, just don't know where to put it or send it...
Change your code like, that is all I think
Program.cs
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule(new IoCConfigurator());
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup.cs
public class Startup
{
public IConfiguration Configuration { get; }
public ContainerBuilder containerBuilder { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
containerBuilder = new ContainerBuilder();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}

ASP.NET core - middleware on MVC

I try to create an asp.net core web api on macOS.
But my middleware isn't called on mvc-call.
My Config:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BackendDbContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//app.UseStaticFiles();
app.UseMvc();
app.UseMiddleware<AuthMiddleware>();
BackendDbInitializer.Init(context);
}
And my Middleware:
public class AuthMiddleware
{
private readonly RequestDelegate _next;
public AuthMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Invoke......................");
await _next.Invoke(context);
}
}
When i do a HTTP-request, that doesn't match a controller request. The middleware class is called.
How can i set up that the middleware class is only called on a mvc-request.
You can use middleware as MVC filters:
public class HomeController : Controller
{
[MiddlewareFilter(typeof(AuthMiddleware))]
public IActionResult Index()
{
return View();
}
}
In this case, AuthMiddleware will run each time the action method Index is called.
PS: You need to install this package (Microsoft.AspNetCore.Mvc.Core)
more info (see Middleware as MVC filters section)

WebApi controller isn't found

I have an example controller in my WebApi-project:
public class MilestonesController : ApiController
{
// GET api/milestones
public IEnumerable<string> Get()
{
return new string[] { "M#1", "M#2" };
}
// GET api/milestones/5
public string Get(int id)
{
return "M with {id}";
}
// POST api/milestones
public void Post([FromBody]string value)
{
}
// PUT api/milestones/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/milestones/5
public void Delete(int id)
{
}
}
If I try to navigate to it:
http://localhost:59493/api/milestones
I always get the error:
No HTTP resource was found that matches the request URI 'http://localhost:59493/api/milestones'.
No type was found that matches the controller named 'milestones'.
Thank you in advance!
Edit:
my WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.asax:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Possible Solution:
I have deleted my project and I've created a new one (WebAPi project) and now it works. The WebApiConfig etc was the same, so I don't really know what was wrong with my first try
you're missing the 'api' section of the url from your route. Try something more like;
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Take a look at where you created that controller. Maybe it is not in the Controllers folder, different namespace or that controller class is nested into another class

Getting "The resource cannot be found." error when using Ninject

I'm working on an ASP.NET MVC 3.0 application, using Ninject as my dependency injection framework.
So I've inherited my controller from NinjectHttpApplication like so:
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
}
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new NinjectDependencyResolver(Kernel));
}
protected override Ninject.IKernel CreateKernel()
{
return new StandardKernel(new QueriesModule());
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" },
new string[] { typeof(HomeController).Namespace }
);
}
}
But whenever I run the application and try to browse to any of my controllers, I get the error:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Home/Index
What's causing this and how do I fix it?
Turns out this was occurring because the NinjectHttpApplication class from which I'm inheriting is calling the OnApplicationStarted() method at startup. So the solution is to remove the Application_Start() method and move all that code into OnApplicationStarted().

Resources