One resource file per language for entire asp.net core project - asp.net-core-mvc

Is it possible to just have only one resource file (per language) for the entire project in stead of per controller and per view (as mentioned in the manual https://docs.asp.net/en/latest/fundamentals/localization.html)?
A resource file per controller and language seems a bit overkill.

Yes, that is possible. You've to override StringLocalizer and StringLocalizerFactory. With those custom you can store resource in one or many files, in the database or in the JSON files. Or do other magic...
And then all you need to do is to register your custom service:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IStringLocalizerFactory, YOUR_LOCALIZER_FACTORY>();
}

Related

How to use controllers and views in another project in ASP.NET Core

If I have set up a project with lots of controllers and views, how could I use them in another project in ASP.NET Core? I tried refering the project but when I use the views in previous project it just return NOT FOUND.
While it is reasonable to create your own ControllerFactory, I found it more convenient to define all my Controllers in each project, but derive them from Controllers in my Shared project:
namespace MyProject1.Controllers
{
public class MyController : MySharedProject.Controllers.MyController
{
// nothing much to do here...
}
}
namespace MySharedProject.Controllers
{
public abstract class MyController : Microsoft.AspNetCore.Mvc.Controller
{
// all (or most) of my controller logic here...
}
}
This has the added benefit that you have a place to put your Controller logic that differs from project to project. Also, it is easier for other developers to quickly find your Controller logic because the Controllers exist in the standard place.
Regarding whether this is advisable, I think it absolutely is. I've created some common Account Management logic that I want to share between projects that otherwise have very different business logic. So I'm sharing my Account and Admin Controllers, but the other Controllers are specific to their respective projects.

Spring: How can I keep routes in sync with URLs on the page?

How can I keep links in my UI templates (e.g. Thymeleaf templates) in sync with the corresponding request mappings in my Spring application?
I've seen that e.g. the Play framework uses the #router-Object within its templates. How is it solved by Spring?
One example:
Spring Controller - simple
#Controller
public class UserController {
#GetMapping("/users/{username}")
public String getUser(#PathParam String username) {
// do some stuff....
return "user";
}
}
HTML-Page
<body>
User details
</body>
Now I want to change "/users" to "/accounts". I'm pretty sure that I've got to update every html page by hand to update the link. Is there an easier solution for this?
As far as I know, there is no simple way to do this with built-in tools from Spring. However, I don't think that this would be too hard to build. You would need the following:
A YAML file with all of your URL templates defined
A Properties Spring bean that contains your URL mappings (read from the YAML file)
All of your #RequestMapping annotations would have to be prop values; i.e.
#GetMapping("${urls.users.byUsername}")
A custom tag that knows about the Properties bean and can create URLs from the templates that were defined in your YAML file.

How to serve an html file with .html url extension using Spring

I'm trying to use the Application Security on Cloud provided by Bluemix for a Spring application.
I'm relatively new to Spring and I'm having difficulty serving the requested verification file with the requested url. Bluemix wants the html file to be available at /IBMDomainVerification.html
However, I can't figure out how to serve the html file given that exact url using Spring. I can serve it without the .html at the end of the url but that's not what it needs.
If anyone can let me know how I can serve the html file given the specified url with the .html extension on the end that'd be great!
Thanks!
Spring 4.1 introduced the ResourceResolvers, that can resolve resources, given their URL path. In particular you could use the simplest: PathResourceResolver. This is the simplest resolver and its purpose is to find a resource given a public URL pattern. In fact, if no ResourceResolver is added to the ResourceChainRegistration, this is the default resolver.
Consider the following example:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/","/other-resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
The above code serves anything in either the webapp/resources of the webapp/other-resources folder, required with URLs /resources/** (e.g. /resources/foo.js). Note the two asterisks, it means that it will match everything after resources/, even '/'.
In your case using /IBMDomainVerification.html (/**) it should work.
An alternative way could be using *<mvc:resources/>* (Spring 3) which can be used to serve static resources while still using the DispatchServlet on root. Please refer to this SO answer.

How to add new DLL locations to WebAPI's controller discovery?

ASP.NET WebAPI has a much appreciated ability to discover ApiController classes in external DLLs even if those DLLs are not referenced. For example, I may have MyWebApiProject that has a set of ApiControllers. I could then create a completely separate project called MyApiProjectPlugin that contains ApiController classes also. I have been able to add the MyApiProjectPlugin.dll file to the bin folder with the first MyApiProject.dll and the original project will discover all the controllers in the plugin project. I really like that ability.
However, What I would like to do is be able to add the plugin project to a sub directory inside of the bin folder. Something like bin/plugins. When I tried this, the original MyApiProject was unable to discover the plugin's controllers.
Is there a simple way to get WebAPI to look for ApiController classes in the bin's subdirectories? If I can avoid rewriting a controller factory from scratch I would like to.
You can write an assembly resolver.
public class PluginsResolver : DefaultAssembliesResolver
{
public override ICollection<Assembly> GetAssemblies()
{
List<Assembly> assemblies = new List<Assembly>(base.GetAssemblies());
assemblies.Add(Assembly.LoadFrom(#"<Path>\MyApiProjectPlugin.dll"));
return assemblies;
}
}
In the Register method in WebApiConfig, register the resolver.
config.Services.Replace(typeof(IAssembliesResolver), new PluginsResolver());

asp.net mvc - common code to execute when loading any page from the application

Where would such code go? Is there a commonly executed block inside Asp.net mvc 3 application - something that gets executed every time any page is loaded?
You can do this by two ways:
First, you can inherit a base Controller from System.Web.Mvc.Controller. Then you use this base class inherits for your application. By this way, you can handle all action executions by overriding OnActionExecuting method of your base controller.
Second and better solution is using Custom Action Filters. Create a custom filter and register it globally in Global.asax file like this:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new YourCustomFilter());
}
Global.asax (ex: http://www.dotnetcurry.com/ShowArticle.aspx?ID=126) or inside the _Layout, it depends on what you're doing.
Just so you know the Global.asax file is also available in ASP.NET Webforms.

Resources