I wanna read session value in ASP.Net Core. If anyone have idea or suggestion please help.
Thanks.
I wanna read session value in ASP.Net Core. If anyone have idea or suggestion please help.
Thanks.
In a razor view that makes a reference to a class in the class library I get this error :
However in the controller action that returns this view I can access the class fine.
Am I missing something.
Hi,
I am building a video game help site. It runs similar to a store shop website. Its connected to a SQL Server under one database with about 5 tables.
Using some of the MSDN tutorials, I have had successfully joined several of the tables using LINQ, and displayed the data right down to the details page.
The issue that is stumping me, is that I need to now want to bring in related data (from several tables). This data has a one with many relationships. From what I gathered you can not bring this into a single view? The only way I have had some success, is when I joined all the needed tables. The output was the tables with single data entries being stamped out repeatedly over and over, for every related entry in the tables with multiple relationships.
I am looking to get guided in the right direction, as I might not be using the right terminology, or could be shown an example, etc. I feel like the answer is in front of me, but I am looking in the wrong spot.
Thank you in advance,
Some of my code below:
Tables:
(Everything revolves around GameId)
Game - Contains title, about information and locations to cover image
Pricelist - Price information
PlayerGameRating - Rating of 1 to 5, per player, per game.
GameMedia - Zero to Unknown number of entries containing video/picture location, title and description.
GameHelp - Zero to Unknown number of entries containing video/picture location, title and description.
Code:
GamesController.cs (Contains just the details to display whole library and the detail page.)
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using GameCloud.Models; using GameCloud.Models.GamesViewModels; using System.Dynamic; using System.Data.SqlTypes; namespace GameCloud.Controllers { public class GamesController : Controller { private readonly GameCloudContext _context; public GamesController(GameCloudContext context) { _context = context; } // GET: Games public async Task<IActionResult> Index(string sortOrder, string searchString, string currentFilter, int? page) { ViewData["CurrentSort"] = sortOrder; ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "title_desc" : ""; ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date"; ViewData["DevSortParm"] = String.IsNullOrEmpty(sortOrder) ? "dev_desc" : ""; ViewData["GenreSortParm"] = String.IsNullOrEmpty(sortOrder) ? "genre_desc" : ""; if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewData["CurrentFilter"] = searchString; var gamerating = from r in _context.PlayerGameRating group r by r.GameId into gameAvg select new { GameId = gameAvg.Key, AverageRating = gameAvg.Average(p => (decimal?)p.RatingStars ?? 0) }; var finalrating = from gameInfo in _context.Game join rate in gamerating on gameInfo.GameId equals rate.GameId into gj from subgame in gj.DefaultIfEmpty() select new { gameInfo.GameId, gameInfo.GameTitle, gameInfo.GameReleaseDate, gameInfo.GameRating, gameInfo.GameStudio, gameInfo.GameSynop, gameInfo.GameGenre, gameInfo.GameAssests, AverageRating = (subgame == null ? 0 : subgame.AverageRating) }; var Qry = from c in finalrating join g in _context.PriceList on c.GameId equals g.GameId //orderby c.GameReleaseDate descending select new GameLibViewModel() { GameId = c.GameId, GameTitle = c.GameTitle, GameReleaseDate = c.GameReleaseDate, GameReleaseDate2 = c.GameReleaseDate, GameAssets = c.GameAssests, GameRating = c.GameRating, GameSynop = c.GameSynop, AverageRating = c.AverageRating, Studio = c.GameStudio, Genre = c.GameGenre, Price = g.RetailCdn, PriceUs = g.RetailUsd }; if (!String.IsNullOrEmpty(searchString)) { Qry = Qry.Where(s => s.GameTitle.Contains(searchString) || s.Studio.Contains(searchString)); } switch (sortOrder) { case "title_desc": Qry = Qry.OrderByDescending(s => s.GameTitle); break; case "dev_desc": Qry = Qry.OrderByDescending(s => s.Studio); break; case "Date": Qry = Qry.OrderBy(s => s.GameReleaseDate2); break; case "date_desc": Qry = Qry.OrderByDescending(s => s.GameReleaseDate2); break; case "genre_desc": Qry = Qry.OrderByDescending(s => s.Genre); break; default: Qry = Qry.OrderByDescending(s => s.GameReleaseDate2); break; } int pageSize = 4; return View(await PaginatedList<GameLibViewModel>.CreateAsync(Qry.AsNoTracking(),page ?? 1, pageSize)); } public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } //WORKING var gamerating = from r in _context.PlayerGameRating group r by r.GameId into gameAvg select new { GameId = gameAvg.Key, AverageRating = gameAvg.Average(p => (decimal?)p.RatingStars ?? 0) }; var finalrating = from gameInfo in _context.Game join rate in gamerating on gameInfo.GameId equals rate.GameId into gj from subgame in gj.DefaultIfEmpty() select new { gameInfo.GameId, gameInfo.GameTitle, gameInfo.GameReleaseDate, gameInfo.GameRating, gameInfo.GameStudio, gameInfo.GameDevsite, gameInfo.GameLocPage, gameInfo.GameExtSynop, gameInfo.GameGenre, gameInfo.GameAssests, AverageRating = (subgame == null ? 0 : subgame.AverageRating) }; var Qry = from c in finalrating join g in _context.PriceList on c.GameId equals g.GameId where c.GameId == id select new SingleGameViewModel() { GameId = c.GameId, GameTitle = c.GameTitle, GameReleaseDate = c.GameReleaseDate, GameAssets = c.GameAssests, GameRating = c.GameRating, GameSynopExt = c.GameExtSynop, AverageRating = c.AverageRating, Studio = c.GameStudio, StudioSite = c.GameDevsite, GameSite = c.GameLocPage, Genre = c.GameGenre, Price = g.RetailCdn, PriceUs = g.RetailUsd }; var game = await Qry .SingleOrDefaultAsync(m => m.GameId == id); if (game == null) { return NotFound(); } return View(game); } } }
Partial View Detail Page:
@using Microsoft.AspNetCore.Mvc.ViewFeatures @using GameCloud.Models.GamesViewModels @model SingleGameViewModel<div class="body-content"> @{ ViewData["Title"] = "Details"; } <h2>Details</h2><div><h4>Game</h4><hr /><dl class="dl-horizontal"><dt> @Html.DisplayNameFor(model => model.GameTitle)</dt><dd> @Html.DisplayFor(model => model.GameTitle)</dd><dt> @Html.DisplayNameFor(model => model.GameAssets)</dt><dd><a href="@Html.DisplayFor(model => model.GameSite)"><img src="@Html.DisplayFor(model => model.GameAssets)" alt="Cover" /></a></dd><dt> @Html.DisplayNameFor(model => model.Studio)</dt><dd><a href="@Html.DisplayFor(model => model.StudioSite)">@Html.DisplayFor(model => model.Studio)</a></dd><dt> @Html.DisplayNameFor(model => model.GameReleaseDate)</dt><dd> @Html.DisplayFor(model => model.GameReleaseDate)</dd><dt> @Html.DisplayNameFor(model => model.Genre)</dt><dd> @Html.DisplayFor(model => model.Genre)</dd><dt> @Html.DisplayNameFor(model => model.GameRating)</dt><dd> @Html.DisplayFor(model => model.GameRating)</dd><dt> @Html.DisplayNameFor(model => model.AverageRating)</dt><dd><p>@Html.DisplayFor(model => model.AverageRating) out of 5</p></dd><dt> @Html.DisplayNameFor(model => model.Price)</dt><dd> @Html.DisplayFor(model => model.Price)</dd><dt> @Html.DisplayNameFor(model => model.GameSynopExt)</dt><dd> @Html.DisplayFor(model => model.GameSynopExt)</dd></dl></div><div id="media"> Related Media Goes Here</div><div id="media"> Related Help Media Goes Here</div><div><a asp-action="Index">Back to List</a></div></div>
ViewModel For Details:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace GameCloud.Models.GamesViewModels { public class SingleGameViewModel { [Key] public int GameId { get; set; } public string GameAssets { get; set; } /// <summary> /// /// </summary> public string GameTitle { get; set; } /// <summary> /// /// </summary> public string GameRating { get; set; } /// <summary> /// /// </summary> public string Genre { get; set; } /// <summary> /// /// </summary> public string Studio { get; set; } public string StudioSite { get; set; } public string GameSite { get; set; } /// <summary> /// /// </summary> /// public string GameSynopExt { get; set; } [DisplayFormat(DataFormatString = "{0:MMM/dd/yyyy}", ApplyFormatInEditMode = true)] public DateTime? GameReleaseDate { get; set; } [DisplayFormat(DataFormatString = "{0:0.0}")] public decimal AverageRating { get; set; } /// <summary> /// Below are commented out attempts when I tried to bring the related data in /// </summary> /// /*public decimal Price { get; set; } public decimal PriceUs { get; set; } public ICollection <GameHelp> GameHelps { get; set; } public virtual ICollection<GameMedia> GameMedias { get; set; } public virtual Game Game { get; set; } public IEnumerable<GameHelpViewModel> _GameHelp { get; set; }*/ // public IEnumerable <GameHelp> GameHelp { get; set; } /* public int GameHelpId { get; set; } public string GameHelpTitle { get; set; } public string GameHelpSynop { get; set; } public string GameHelpLink { get; set; } public string GameHelpIcon { get; set; } [DisplayFormat(DataFormatString = "{0:MMM/dd/yyyy}")] public DateTime? CreateStamp { get; set; }*/ } }
Sir
Does there any IDE or Tool for Data Modeling in ASP.NET CORE development?
Because I am newbee and finding it difficult to do it.
Regards
I intermitently get an error at the same line of code in a ASP.NET core web application, it is calling a function in a class library. It works the vast majority of the time but sometimes gives the error below.
The exact same code has been used from a ASP.NET 4.6 web app for a long time and never had this problem with that.
I found the article "Set up a hosting environment for ASP.NET Core on Linux with Apache, and deploy to it"https://docs.microsoft.com/en-us/aspnet/core/publishing/apache-proxy . But it describes the configurations for CentOS 7. But I need the settings for Ubuntu 16.04. Who set up? Help with settings please
Hi,
I could use some assistance using the data protection APIs.
I have an MVC5 site using forms authentication, and have configured the SystemWeb data protector replacement with the startup class registered below.
public class MyAppDataProtectionStartup : DataProtectionStartup { public override void ConfigureServices(IServiceCollection services) { var path = ConfigurationManager.AppSettings["DataProtectionKeyPath"].ToString(); if (!Path.IsPathRooted(path)) { path = HostingEnvironment.MapPath(path); } services.AddDataProtection() .SetApplicationName("myapp") .PersistKeysToFileSystem(new System.IO.DirectoryInfo(path)) .UseCryptographicAlgorithms(new AuthenticatedEncryptionSettings() { EncryptionAlgorithm = EncryptionAlgorithm.AES_256_GCM, ValidationAlgorithm = ValidationAlgorithm.HMACSHA512 }); } }
This is functional, and I can clearly see that my authentication cookie is being encrypted through the data protection APIs.
I also have an asp.net core app running on subdomain.myapp.com. The auth cookie domain is set properly so that my core app receives the auth cookie on requests. The startup.cs ConfigureServies method has the following code:
public void ConfigureServices(IServiceCollection services) { services.AddDataProtection() .SetApplicationName("myapp") .PersistKeysToFileSystem(new System.IO.DirectoryInfo(samepathasabove)) .UseCryptographicAlgorithms(new AuthenticatedEncryptionSettings() { EncryptionAlgorithm = EncryptionAlgorithm.AES_256_GCM, ValidationAlgorithm = ValidationAlgorithm.HMACSHA512 }); }
On request, I am able to grab the cookie, and use the dataprotecionprovider to decrypt the cookie, but I get an CryptographicException: the provided payload cannot be decrypted because it was not protected with this protection provider.
In debug mode, I have checked the DataProtector application name, protector purpose and secondary purposes, mode, and even the data in the aadtemplate, and in both environments all data is identical.
Is there any other discriminator that I should be looking for? I am at a loss!
Thanks in advance
Hi
I've got a StartDate propetry in my ServiceItem defined like this:
[DataType(DataType.Date)] [Required] public DateTime? StartDate { get; set; }
Then when I try to serialize SubscriptionServiceItem into Json using:
return Json(Mapper.Map<SubscriptionServiceItemDto>((await _context.ServiceItems.OfType<SubscriptionServiceItem>().Where(g => g.Id == id && g.IsArchived == false).ToListAsync()).First()));
I get the following response
"startDate": "2013-05-11T00:00:00",
Is it possiblie in ASP.NET Core to format the JSON result for that particular property like this:
"startDate": "2013-05-11",
Does anyone know where I can get a copy of the 1.0.1 with SDK Preview 2 build 3131 for windows? The github page only has 1.0.1 with SDK Preview 2 build 3131 and 3133, which has version 3133 for windows and 3131 for all the other platforms. This is an issue
when you develop locally on windows using 3133 and on the server have 3131 since it is specified in the global.json file. Upgrading isn't currently and option.
I used to have 3131 for windows as I installed it early on, but I can't seem to find it anywhere. For further context it seamed to work fine until installed the 1.0.4 with SDK 1.0.1 build then it give me errors until I Update the global.json to point
specifically at 3133.
Hi,
There have any examples in Q R Code Generator in ASP.NET Core ?
Hi everyone,
I'm making a website which uses ASP.NET Core as a back-end for video/audio streaming.
VideoController.cs
public class VideoController: Controller { // Singleton registered at Startup.cs private readonly IStreamingService _streamingService; private readonly IHostingEnvironment _hostingEnvironment; public VideoController(IStreamingService streamingService, IHostingEnvironment hostingEnvironment) { _streamingService = streamingService; _hostingEnvironment = hostingEnvironment; } [HttpGet("initiate")] public IActionResult Initiate() { _streamingService.Connections.Add(Response.Body); } [HttpPost("broadcast")] public async Task<IActionResult> Broadcast() { // Retrieve data submitted from POSTMAN. var data = _streamingService.AnalyzeStream(Request.Body); foreach (var stream in _streamingService.Connections) { try { await stream.WriteAsync(data, 0, data.Length); } catch (Exception exception) { stream.Dispose(); _streamingService.Connections.Remove(stream); } } } }
StreamingService.cs
public class StreamingService: IStreamingService { public IList<Stream> Connections {get;set;} public StreamingService() { Connections = new List<Stream>(); } // Read all bytes from stream. public byte[] AnalyzeStream(Stream stream) { long originalPosititon = 0; if (stream.CanSeek) { originalPosititon = stream.Position; stream.Position = 0; } try { var readBuffer = new byte[4096]; int bytesReader; while ((byteRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) { totalBytesRead += byteRead; if (totalBytesRead == readBuffer.Length) { var nextByte = stream.ReadByte(); if (nextByte != -1) { var temp = new byte[readBuffer * 2]; Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); Buffer.SetByte(temp, totalBytesRead, (byte)nextByte); readBuffer = temp; totalBytesRead++; } } } var buffer = readBuffer; if (readBuffer.Length != totalBytesRead) { buffer = new byte[totalBytesRead]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); } return buffer; } finally { if (stream.CanSeek) stream.Position = originalPosititon; } } }
Index.cshtml
<div><video width="480" height="320" controls="controls" autoplay="autoplay"><source src="/api/video/initiate" type="video/mp4"></source></video></div>
In VideoController.cs, when I called
await stream.WriteAsync(data, 0, data.Length);
I got an exception which told me the stream has been disposed.
My question is :
- How can I keep the connection alive as long as the web browser opens, and close the stream after a long time of idling. (Stream on demand)
Thank you,
P/S; I've read some tutorials about streaming on ASP.NET, most of them are about streaming a static file back to client, but I want to stream from mobile devices.
Hi,
I want to filter the database by the id:
public async Task<IActionResult> Index(int? id)
{
var viewModel = new ShopIndexData()
{
Categories = await _context.Category
.Include(c => c.ShopAssignments)
.Include(s => s.ShopSortAssignment)
.AsNoTracking()
.ToListAsync()
};
return View(viewModel);
}
How do I do that?
Poul Erik
Hmmm...
I am loading a Create view as:
public IActionResult QuoteSalesProcedure(int id) { ViewData["FrequencyID"] = new SelectList(_context.Frequency.OrderBy(i => i.iFrequency), "FrequencyID", "iFrequency"); ViewData["ProcedureID"] = new SelectList(_context.Procedures.OrderBy(p => p.ProcedureName), "ProcedureID", "ProcedureName"); ViewData["QuoteID"] = new SelectList(_context.Quote.Include(q => q.QuoteRequest).OrderBy(q => q.QuoteRequest.QDescription),"QuoteID", "QuoteRequest.QDescription", id); return View(); }
This works fine. It passes in a default value for the quote being worked on.
From the view I want to load a component view, showing procedures already included in the quote. to do this I need to call the view component something like:
<div>@await Component.InvokeAsync("QuoteProcedures", new {id==id})</div>
However I don't see how to pass the id value to the view. I am sure it is simple, and I am overthinking it. Can I get the Quote ID from the viewbag somehow? Or do I somehow pass the value as a numeric in the controller to the view? Or is there a better option?
This is a web api method that worked fine in a asp.net 4.x mvc web app for ages but i'm putting it into a asp.net core web app. Its just a GET request and if you browse to it Chrome it appears to bring back all the JSON OK but the request never actually completes, there is a spinner icon on the browser that goes on and on and in developer tools it says status failed "ERR_CONNECTION_RESET"
I can't understand why the API call is acting like this.
Hi,
I am using cookies middleware authentication in ASP.Net core project.I want to know default timeout value for 'CookieAuthenticationOptions.ExpireTimeSpan'.
Also It would be great if anyone can specify default flag value for 'CookieAuthenticationOptions.SlidingExpiration'.
I am not able to get official default values for CookieAuthenticationOptions anywhere. So any help in this regard would be great.
Thanks,
Shashikant
I'm trying to set Core MVC Rewrite so:
localhost/partis requested, it responds with the default
localhost/part/index.html
localhost/part/[anything], then still responds with
index.html(
localhost/part/index.html)
Here's what I have now:
app.UseRewriter(new RewriteOptions().AddRewrite("part(\\/.*)?", "part/index.html", true)); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(...);
So now, when
localhost/part/[anything]/[something]is requested, it does serve
index.html. But it serves it as
localhost/part/[anything]/[something]/index.htmland this is a problem with Angular's BASE_HREF. So app showsLoading... and nothing else is loaded obviously. Hm... This requires a fix from Angular's part. And I have no idea for the fix right now. Anyone?
I'm in the process of getting to grips with ASPNET CORE [version 1.1, using VS2017 Community, version 15.1 (26403.3)]I've created a working ViewComponent called
UserDetails
(abbreviated below):
namespaceAdminConsole.ViewComponents{[ViewComponent(Name="UserDetails")]publicclassUserDetailsViewComponent:ViewComponent{...does stuff...}
and I can invoke it successfully in a view by using
@awaitComponent.InvokeAsync("UserDetails")
I'd rather invoke it by using a TagHelper, but it just ain't happening. I've trawled through StackOverflow and other helpful pages, and whilst others seem to get it to work, I can't.
I've added the line
@addTagHelper "*, AdminConsole"
in _ViewImports.cshtml and
<vc:user-details></vc:user-details>
in the view I want to render the VC in, and it does not render; I don't get an error, it just doesn't render.
If I change the TagHelper declaration to
@addTagHelper *, AdminConsole
(without the speech marks) it also does not render or error.
If I try both combinations as above and try
<vc:UserDetails></vc:UserDetails>
i.e. without the kebab-case, it does not render or error.
My
_ViewImports.cshtml
is as follows
@usingAdminConsole@usingAdminConsole.Models@usingAdminConsole.Models.AccountViewModels@usingAdminConsole.Models.ManageViewModels@usingMicrosoft.AspNetCore.Identity@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers@injectMicrosoft.ApplicationInsights.Extensibility.TelemetryConfigurationTelemetryConfiguration@addTagHelper"*, AdminConsole"
Using the full namespace for the VC in the
@addTagHelper
declaration (
AdminConsole.ViewComponents
) produces a
cannot resolve TagHelper
error.
I think I've tried all permutations, and documentation from official and community sources only suggest what I've tried (and differ!). I would be very grateful if someone could help shed some light.
I have a requirement where I need to authorize internal users via Azure AD and external users via Individual User Accounts in my .Net core application (I cannot use Azure B2C for external users). Is this possible? When I create a new application I can only select one method.
Is it possible to have the Individual User Account scheme access Azure AD like it can with Google or Facebook accounts?
Any help is most appreciated.
Both of these radio buttons will have checked="checked" on them. Why would the tag helper add that. How do you specify that none of them should be checked?
<div class="form-group">
<label>
<input name="Answer" type="radio" asp-for="Answer1" value="@Model.Answer1" /> @Model.Answer1
</label>
</div>
<div class="form-group">
<label>
<input name="Answer" type="radio" asp-for="Answer2" value="@Model.Answer2" /> @Model.Answer2
</label>
</div>
Hi,
I load a view through action http://localhost/Home/Test which includes some javascript files located in my wwwroot folder ( href="/js/base.js" which points tohttp://localhost/js/base.js ).
In base.js I try to load some additional files and I have a relative path to "user.json" which should point to http://localhost/js/user.json but it does not. It tires to load user.json inhttp://localhost/Home/Test/user.json.
How can I fix this issiue?
Thanks