Locally my project runs fine but when I deploy on Azure using a web app, I get the following error when it starts:
MissingMethodException: Method not found: 'Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter.get_SerializerSettings()'.
SmartAdmin.Startup.<>c.b__13_7(MvcOptions options)
I've tried this:
services.AddMvc(options =>
{
options.Filters.Add(new UserPreferencesLoaderAtrribute());
var jsonFormatter = (JsonOutputFormatter)options.OutputFormatters.FirstOrDefault(f => f is JsonOutputFormatter);
if (jsonFormatter != null)
{
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
});
And this:
services.AddMvc(options =>
{
options.Filters.Add(new UserPreferencesLoaderAtrribute());
}).AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Yes, I just worked all night and did eventually figured it out. Here is what you need to do:
Make sure you install:
-Microsoft.AspNet.Mvc.Formatters.Json version "6.0.0-rc1-final"
and
-Revert Netonsoft.Json to "6.0.6".
Then you can keep this:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
project.json:
"Microsoft.AspNet.Mvc.Formatters.Json": "6.0.0-rc1-final",
"Newtonsoft.Json": "6.0.6"
I had a bunch of trouble redeploying too but eventually this worked.
Good luck!
Just got off a call with Microsoft support as of yesterday (02 Aug 2016) Azure App Services now only support ASP.NET core, due to a breaking change:
A breaking change was released and anything other than ASP.NET core is not supported, so the only option is an upgrade. The breaking change is being rolled out to all (regions) eventually all your instances will fail.
Is ASP.NET 5, Core RC1, RC2 supported on Azure App Service? NO
https://blogs.msdn.microsoft.com/waws/2016/06/14/supporting-asp-net-5-core-rc1-on-azure-app-service/
Verify your app is running the latest version of ASP.NET Core and not RC1 or RC2.
We were affected (North Europe) and upgraded our app from RC2 and it worked first time.
We also saw this in production, contacted the team and got this out: https://social.msdn.microsoft.com/Forums/en-US/f0a6bbaf-498a-4c1f-b869-6779ee18e04e/app-service-applications-may-experience-methodnotfound-exceptions-due-to-incorrect-newtonsoft-json?forum=windowsazurewebsitespreview
It appears that a fix for App Service is on its way as well. Meanwhile, the linked post contains pretty much the same instructions as the other answers here.
Related
How can I make sure that the users of a Blazor client app always load the latest version of the code? I now have to instruct them to clear their browser caches every time a new version is published. This hampers the "release early and often" approach and I simply cannot believe that any serious blazor development is at all possible without checking for new versions at start up (what click once applications do).
I found this solution on https://learn.microsoft.com/en-us/answers/questions/214424/blazor-wpa-not-updating.html
/**
* Register Service Worker
*/
navigator.serviceWorker
.register('/***.js', { scope: '/' })
.then(() => {
console.log('Service Worker Registered');
});
This js file can contain a cache version like below.
const CACHE_VERSION = 1.0
But that is too cryptic for me? How can I implement the solution stated above as in "for dummies"?
The answer is (once you know it) quite simple:
In the index.html under the wwwrootfolder you will find:
<script>navigator.serviceWorker.register('service-worker.js');</script>
Below this write:
<script>navigator.serviceWorker.register('version.js');</script>
And create a "version.js" file in this folder with as single content:
const CACHE_VERSION = 1.0
Increment the 1.0 value each time you want your clients to load the new version.
It looks like this:
Once your clients have managed to clear their cache and load the version that contains this code, a simple reload or shut down and restart of the browser will make the new version active.
I'm developing a cross-platform (win/mac/linux) application and I'm looking to store my application state. What is the .NET Core recommended way of doing this?
I've dug through the documentation and the closest thing I found was this, which is aimed at Visual Studio/.NET Framework (and I'm on VS Code).
There are 3 ways,
ONLY For Localhost
Simply stash them in your appsettings.json or as environment
variables.
For Staging / Production,
Azure Key Vault
By utilising Azure Key Vault and the Microsoft.Extensions.Configuration.AzureKeyVault NuGet Package, you will be able to stash configurations for your projects in the best way possible in the actual environment.
You then simply inject it in,
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var root = config.Build();
config.AddAzureKeyVault(
$”https://{root["KeyVault:Vault"]}.vault.azure.net/",
root[“KeyVault:ClientId”],
root[“KeyVault:ClientSecret”]);
})
.UseStartup<Startup>();
Although you still have to stash those 3 variables in, Azure has Azure AD to enforce access only to specified Applications. Thus, you need to register an application under the Azure AD in order for this to work. There are also restrictive features that will help you sandbox Azure Key Vault further.
Existing Vault Storages
Last but not least, the last way is to utilise existing vault storage options like HashiCorp. Libraries like https://github.com/rajanadar/VaultSharp will help you to implement it quickly and effectively. This is suitable for you if you primarily use a non-Azure provider for your servers.
As described here, you can use appsettings.json, which is generated and referenced within the new project template in dotnet new command
You can use the ConfigurationBuilder from the Microsoft.Extensions.Configuration nuget package
Although the docs are for ASP Core, you should be able to use them in your regular .Net Core app.
Create settings.json:
{
"mysetting": "value",
}
And use it:
var configuration = new ConfigurationBuilder()
.AddJsonFile("settings.json")
.Build();
// get the values from the settings.json
var mySetting = configuration["mysetting"];
Console.WriteLine(mySetting);
I'm exploring ASP.NET Core Web Applocation empty template. And I'm little bit confused there: if I run the application created by VS new project wizard with no changes and break point on WriteAsync method I could see that it runs two times.
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
Does anybody know if this is normal behaviour or a kind of bug?
You can use logging for diagnosing these kind of issues. You can use the Debug logger to see the log messages in the debug output window.
Add the package Microsoft.Extensions.Logging.Debug to your project.json and do the following in Startup.cs's Configure method:
loggerFactory.AddDebug()
Regarding why you are seeing 2 times, I guess one of the requests is for the fav.ico from the browser.
I have an ASP .NET 5 RC1 website to which I am trying to add localization.
Based on the information found I did the following
In the ConfigureService in Startup.cs:
Enable Localization and setting the ResourcePath to "Resources"
Enable View Localization and Enable Data Annotations Localization
//check http://damienbod.com/2015/10/21/asp-net-5-mvc-6-localization/
services.AddLocalization(options => options.ResourcesPath = "Resources");
// Add MVC services to the services container.
//check http://blogs.msdn.com/b/webdev/archive/2015/10/15/announcing-availability-of-asp-net-5-beta8.aspx
services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization();
In the Configure method fin Startup.cs
Setup the list of supported cultures
Enable Request Localization
//check http://www.jerriepelser.com/blog/setting-thread-culture-aspnet5
//check http://damienbod.com/2015/10/21/asp-net-5-mvc-6-localization/
List<CultureInfo> supportedCultures = new List<CultureInfo>()
{
new CultureInfo("en"),
new CultureInfo("es")
};
var requestLocalizationOptions = new RequestLocalizationOptions()
{
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
app.UseRequestLocalization(requestLocalizationOptions, new RequestCulture(new CultureInfo("es")));
Create a Resources folder under the project
Create the Resources for the Controller. With the convention {Project}.{Controllers}.{ControllerClassName}.{culture}.resx
Create the Resources for the Views. With the convention Views.{ViewFolder}.{ViewName}.cshtml.{culture}.resx
Use the IHtmlLocalizer in the controller, and access the item. In this case localizer["Title"], which is found and works just fine. However when the culture is set to "es" it is not found and just falls back to the default resource.
private IHtmlLocalizer<HomeController> _htmlLocalizer;
public HomeController(IOptions<PTIWebPortal.Configuration.PTIWebPortalConfiguration> pConfiguration,
ILoggerFactory factory, IHtmlLocalizer<HomeController> localizer) : base(pConfiguration, factory)
{
this._htmlLocalizer = localizer;
}
The same is happens for the views, it only works with the default resource, but not with the others.
Any ideas on how to fix it?
There are a lot of known issues of things not working for localization as of rc1.
Some of the known issues are tooling related, so some of the localization things work if you run the app from the command line instead of launching from visual studio.
But even from the command line a lot of things that were supposed to work do not work.
There has been quite a bit of work after rc1 and a lot of localization issues have been fixed and closed recently, so things should be much better after rc2 is released sometime in February.
I am trying to build an app with ASP.NET Core (aka vNext). I need to call a third-party REST-API. Traditionally, I would use HttpClient. However, I can't seem to get it to work. In my project.json file I have:
"dependencies": {
"Microsoft.Net.Http.Client": "1.0.0-*"
}
When I run dnu restore, I receive an error that says: "Unable to locate Microsoft.Net.Http.Client >= 1.0.0-*". The other post referred to by the commenter is out-of-date.
I am building this app in Mac OS X. I don't think that makes a difference. Still, Is HttpClient the recommended approach for calling a third-party REST API? If not, what should I be using? If it is, what am I doing wrong?
Thank you!
Did you try Microsoft ASP.NET Web API 2.2 Client Library
Just add reference to your project.json file as below:
"dependencies": {
"Microsoft.AspNet.WebApi.Client": "5.2.3"
}
And after package restore, you can call your Web Api like below:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourapidomain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
var product = await response.Content.ReadAsAsync<Product>();
}
}
You can also find a detailed tutorial at http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
I'm looking at the NuGet page for that package. The earliest version number is 2.0.20505. Your project specifies anything that's 1.0.0-*. Seems like that would exclude a 2.X version. Try just specifying the latest version 2.2.29.
Note that I'm not 100% familiar with how vNext resolves packages, so 1.0.0.0-* could very well pull in a 2.X package, my answer is just a guess based on the syntax. Let me know if it doesn't work and I'll remove my answer.