if i can change the payload of the jwt without it affecting any validation how is it considered secure?
a quick jwt question
ASP.Net 3.1 : Error after updating Nuget Package
I am having Asp.Net 3.1 application, and I am getting error After updating my nuget packages 'Microsoft.EntityFrameworkCore' in below line as
'The specified field '_redirectUris' cannot be used for the property 'ClientApplication.RedirectUrisList' because it does not match the property name.'
modelBuilder.Entity<TestApplication>().Property<string>("RedirectUrisList").HasField("_redirectUris");
How to refresh access token using refresh token?
I can't find a tutorial or a code example where it shows how/when to refresh the access token. How to implement refreshing the new access token when it is about to expire?
This is what I have so far:
This is the class where to get the new access token and refresh token.
namespace DemoApp
{
public class Tokens
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string refresh_token { get; set; }
}
public class AccessToken
{
public void GetNewAccessToken()
{
Tokens localTokens = new Tokens();
var client = new RestClient("www.example.com/api/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&refresh_token=" + localTokens.refresh_token, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var responseContent = response.Content;
var newTokensList = new JavaScriptSerializer().Deserialize<Tokens>(responseContent);
localTokens.access_token = newTokensList .access_token;
localTokens.refresh_token = newTokensList .refresh_token;
}
}
}
This is the class where it call the API, with the new Access Token, to get the new data.
namespace DemoApp
{
public class API
{
public Data()
{
public void CallAPI()
{
Tokens tokens = new Tokens();
var client = new RestClient("www.example.com/api");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer " + tokens.access_token);
request.AddHeader("accept", "application/json; charset=utf-8");
IRestResponse response = client.Execute(request);
var data = response.Content;
}
}
}
}
After form submitted event?
Hi
In my index view, use can add/update order in modal form (via javascript client side code). it works correctly. i want to close modal form & do some actions after form has been submitted.
can anybody help me how to accomplish this task?
Thanks
twofactor sign in issue
Hi
a user logins in with there username and password and i send them a code.
the user is directed to a enter code page.
where and how do i hold the userid?
do i just put it in the url, which seems a little insecure? do i put it in a jwt, which the seems to complicate jwt's (i have to validate the jwt for a status,and not just mean signed in)
or is there another way i am missing
Send Message to Telegram From Asp.net Core
Hi,
i use this code to send message to telegram from asp.net core in web , and its worked
but i don't want enter verify code every time when i want send message
how can i use it without verify code that its send to my phone
var client = new TelegramClient(Api Id, "Api Hash"); await client.ConnectAsync(); var hash = await client.SendCodeRequestAsync("+9809100000000"); var code = "72757"; // you can change code in debugger //code will send via telegram to you TLUser user = null; try { user = await client.MakeAuthAsync("+9809100000000", hash, code); } catch (CloudPasswordNeededException ex) { //if u activate two step verification in telegram var password = await client.GetPasswordSetting(); var password_str = "test"; user = await client.MakeAuthWithPasswordAsync(password, password_str); } if (client.IsUserAuthorized()) { //get available contacts var result = await client.GetContactsAsync(); //find recipient in contacts var userr = result.Users.ToList() .Where(x => x.GetType() == typeof(TLUser)) .Cast<TLUser>() .FirstOrDefault(x => x.Username == "*******"); //send message await client.SendMessageAsync(new TLInputPeerUser() { UserId = userr.Id }, "Hello "); }
How can I limit the text input only to allow English characters and numbers?
These days I am working hard on blazor server-side for validation.
Here are my codes:
public class ModelClass {
[Required]
public string Code { get; set; }
}
public ModelClass Model { get; set; } = new ModelClass();
private void HandleValidSubmit()
{
//
}
<EditForm Model="@Model " OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText id="input_text" @bind-Value="Model.Code" />
<input type="submit" class="input_submit" value="Continue" />
</EditForm>
The Required attribute is used to limit the text input is not null. Now I want to limit the text input only to allow English characters and numbers.
It seems there are not any other attributes that can do it. How can I solve this? Thank you.
Problem with relationship between User (testTaker) and Question while writin LINQ in action
Hi guys,
I develop Quiz application where users can login and take test. My problem is that I cannot write right action in controller so that when each user submit their answer while they are logged in, and if it's true, the relevant question score for each user must be saved in database. Each user holds testTakerId , and there is many-to-many relationship between TestTaker and Question object as all test takers will have many questions and each question will concern all test takers. So, considering this, my model is like this:
Question
public class Question { public Question() { Answers = new HashSet<Answer>(); } public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public Exam Exam { get; set; } public int ExamId { get; set; } public TimeSpan? Remainedtime { get; set; } public int Score { get; set; } public ICollection<Answer> Answers { get; set; } public ICollection<UserQuestion> UserQuestions { get; set; } }
ExamUser
public class ExamUser: IdentityUser { public TestTaker TestTaker { get; set; } public int? TestTakerId { get; set; } }
TestTaker
public class TestTaker { public int Id { get; set; } [Required] public string Name { get; set; } public string Phone { get; set; } public string Education { get; set; } public string Job { get; set; } public DateTime Birth { get; set; } public ExamUser ExamUser { get; set; } public int Result { get; set; } public ICollection<UserQuestion> UserQuestions { get; set; } }
UserQuestion (moderate table for many-to-many relationship)
public class UserQuestion { public int TestTakerId { get; set; } public TestTaker TestTaker { get; set; } public int QuestionId { get; set; } public Question Question { get; set; } }
The reason why I didn't connect ExamUser directly to questions is that its built in Id is string (it might cause problem while inserting to database).
in DbContext:
public class IntellectDbContext:IdentityDbContext<ExamUser> { public IntellectDbContext(DbContextOptions<IntellectDbContext> dbContextOptions) : base(dbContextOptions) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<UserQuestion>() .HasKey(a => new { a.TestTakerId, a.QuestionId }); modelBuilder.Entity<UserQuestion>() .HasOne(a => a.TestTaker) .WithMany(b => b.UserQuestions) .HasForeignKey(a => a.TestTakerId); modelBuilder.Entity<UserQuestion>() .HasOne(a => a.Question) .WithMany(c => c.UserQuestions) .HasForeignKey(a => a.QuestionId); } public DbSet<Answer> Answers { get; set; } public DbSet<Question> Questions { get; set; } public DbSet<Exam> Exams { get; set; } public DbSet<ExamUser> ExamUsers { get; set; } public DbSet<UserQuestion> UserQuestions { get; set; } public DbSet<TestTaker> TestTakers { get; set; } }
Question View in Exam:
<div class="questioncontainer"> <form asp-action="Question" asp-controller="Home" asp-route-id="@Model.NextQuestion.Id" asp-route-count="@ViewBag.Equestions"><div class="row"><div class="col-lg-3"></div><div class="col-lg-6 col-sm-12"><table><tr><th>Timer</th></tr><tr><td><label asp-for="Question.Remainedtime" id="time"></label><input type="hidden" id="timehidden" asp-for="Question.Remainedtime" /></td></tr></table><div class="question">@Model.CurrentQuestion.Description </div></div><div class="col-lg-3"></div></div><div class="row"><div class="col-lg-3 col-sm-0"></div> @{ int n = 0; } @foreach (Answer item in Model.Answers) { if (n == 0 || n == 2) { @: <div class="col-lg-3 col-sm-12"> @: <div class="firstpart"> }<input asp-for="@item.Id" name="@item.Id" hidden /><input type="radio" asp-for="@item.Id" name="myanswer" value="@item.Id" />@item.Description<br> if (n == 1 || n == 3) { @:</div> @:</div> } n++; }<div class="col-lg-3"></div></div><div class="row"><div class="col-lg-6 col-sm-4"></div><div class="col-lg-3 col-sm-4"></div><div class="col-lg-3 col-sm-4"><div class="nextbtn"> @if (ViewBag.Equestions == 0) {<input type="submit" value="Finish" /> } else {<input type="submit" value="Next" /> }</div></div></div></form></div> @section Script{ <script> var start = Date.now(), diff, seconds; function startTimer(duration) { function timer() { // get the number of seconds that have elapsed since // startTimer() was called diff = duration - (((Date.now() - start) / 1000) | 0); // does the same job as parseInt truncates the float seconds = diff; seconds = seconds < 10 ? "0" + seconds : seconds;$("#time").text(seconds);$("#timehidden").val(seconds); if (diff <= 0) { // add one second so that the count down starts at the full duration // example 05:00 not 04:59 start = Date.now() + 1000; } }; // we don't want to wait a full second before the timer starts timer(); setInterval(timer, 1000); } window.onload = function () { var minute = 60 * @Model.Question.Remainedtime; startTimer(fiveMinutes); $("#time").val("start"); };</script> }
And finally, Controller (the problem is here)
public class HomeController : Controller
{
private readonly IntellectDbContext _intellectDbContext;
private readonly UserManager<ExamUser> _userManager;
private readonly SignInManager<ExamUser> _signInManager;
static int exam_id = 0;
static int? PreviousId = 0;
static int result = 0;
static int correctAnswer = 0;
static List<Question> RemainedQuestions = new List<Question>();
static List<int> trueAnswers = new List<int>();
public HomeController(IntellectDbContext intellectDbContext, UserManager<ExamUser> userManager, SignInManager<ExamUser> signInManager)
{
_intellectDbContext = intellectDbContext;
_userManager = userManager;
_signInManager = signInManager;
}
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
[HttpGet]
public async Task<IActionResult> Test(int Id)
{
exam_id = Id;
AdminViewModel admodel = new AdminViewModel();
admodel.Equestions = await _intellectDbContext.Questions.Include(q => q.Answers).Where(q => q.ExamId == Id).ToListAsync();
admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(q => q.ExamId == Id).FirstOrDefaultAsync();
RemainedQuestions = admodel.Equestions;
PreviousId = admodel.CurrentQuestion.Id;
return View(admodel);
}
public async Task<IActionResult> Question(int Id, int count, int myanswer)
{
AdminViewModel admodel = new AdminViewModel();
admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(x => x.Id == Id).SingleOrDefaultAsync();
admodel.Answers = await _intellectDbContext.Answers.Where(y => y.QuestionId == Id).ToListAsync();
admodel.Equestions = await _intellectDbContext.Questions.Where(q => q.ExamId == exam_id).ToListAsync();
admodel.CurrentQuestion.Remainedtime = new TimeSpan(0, 0, 60);
correctAnswer = _intellectDbContext.Answers.Where(a => a.QuestionId == PreviousId && a.Correct == true).SingleOrDefault().Id;
if(myanswer == correctAnswer)
{
result = int.Parse(admodel.Question.Remainedtime.ToString());
// admodel.CurrentQuestion.Score = result;
}
if (_signInManager.IsSignedIn(User))
{
ExamUser examTaker = await _userManager.GetUserAsync(HttpContext.User);
examTaker.TestTaker = await _intellectDbContext.TestTakers.FirstOrDefaultAsync();
examTaker.TestTaker.UserQuestions = await _intellectDbContext.UserQuestions.ToListAsync();
admodel.CurrentQuestion = examTaker.TestTaker.UserQuestions.Select(u => u.Question).Where(x => x.Id == Id).SingleOrDefault();admodel.CurrentQuestion.Score = result;
}
if (count > 1)
{
var question = RemainedQuestions.Single(r => r.Id == admodel.CurrentQuestion.Id);
PreviousId = question.Id;
RemainedQuestions.Remove(question);
admodel.NextQuestion = RemainedQuestions[0];
count -= 1;
}
else
{
admodel.NextQuestion = RemainedQuestions[0];
count -= 1;
}
if(count == -1)
{
return RedirectToAction(nameof(Finish));
}
ViewBag.Equestions = count;
return View(admodel);
}
}
Please, mainly focus on Question action as this action will do the main job. Result is calculated according to remianed time which will be the question's point. First, while running application, the code I highlighted (admodel.CurrentQuestion.Score = result;) gives null reference exception though I defined it in the code line before it. As moderate table (UserQuestion) shows only Ids in its table in SQLServer, I cannot see actually where each user's question score might be inserted. Only if joining these 3 tables, maybe we can see result if action is done successfully. How can I solve it? Has anyone faced such experience?
Hope, one of you can find solution to this problem. Thanks in advance!
Migration Issue with Npgsql.EntityFrameworkCore.PostgreSQL
Hi,
I have following problem when I try to add a migration:
Premises:
I´m using Net.Core 5.0.0 preview 2
Database PostgreSql last version
Entity framework tools 5.0.0 preview 2
Npgsql.EntityFrameworkCore.PostgreSQL 5.0.0 preview 2
The error:
I add first migration and it is done without problem
The problem I get when I try to update-database and I get following:
PM> add-migration initial Build started... Build succeeded. To undo this action, use Remove-Migration. PM> update-database Build started... Build succeeded. System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.GetColumnType(String schema, String table, String name, ColumnOperation operation, IModel model) at Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.NpgsqlMigrationsSqlGenerator.ColumnDefinition(String schema, String table, String name, ColumnOperation operation, IModel model, MigrationCommandListBuilder builder) at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.ColumnDefinition(AddColumnOperation operation, IModel model, MigrationCommandListBuilder builder) at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.CreateTableColumns(CreateTableOperation operation, IModel model, MigrationCommandListBuilder builder) at Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.NpgsqlMigrationsSqlGenerator.Generate(CreateTableOperation operation, IModel model, MigrationCommandListBuilder builder, Boolean terminate) at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.<>c.<.cctor>b__71_11(MigrationsSqlGenerator g, MigrationOperation o, IModel m, MigrationCommandListBuilder b) at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder) at Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.NpgsqlMigrationsSqlGenerator.Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder) at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.Generate(IReadOnlyList`1 operations, IModel model) at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.GenerateUpSql(Migration migration) at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.<>c__DisplayClass15_2.<GetMigrationCommandLists>b__2() at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Object reference not set to an instance of an object.
the migration is this:
using System; using System.Collections.Generic; using FidaBlazor.Shared.Enums; using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace FidaBlazor.Server.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "BaseLangCodes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), KeyText = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_BaseLangCodes", x => x.Id); }); migrationBuilder.CreateTable( name: "LanguageCodes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Code = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_LanguageCodes", x => x.Id); }); migrationBuilder.CreateTable( name: "Pages", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Name = table.Column<string>(nullable: false), Url = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Pages", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), RoleId = table.Column<int>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), FirstName = table.Column<string>(maxLength: 64, nullable: true), LastName = table.Column<string>(maxLength: 64, nullable: true), BirthDate = table.Column<DateTime>(nullable: false), PlaceOfBirth = table.Column<string>(nullable: true), Gender = table.Column<int>(nullable: false), Thumbnail = table.Column<string>(nullable: true), PhotoUrl = table.Column<string>(nullable: true), IsDisabled = table.Column<bool>(nullable: false), LanguageId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); table.ForeignKey( name: "FK_AspNetUsers_LanguageCodes_LanguageId", column: x => x.LanguageId, principalTable: "LanguageCodes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "LangTranslations", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Translation = table.Column<string>(nullable: true), BaseLangId = table.Column<int>(nullable: false), LangCodeId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_LangTranslations", x => x.Id); table.ForeignKey( name: "FK_LangTranslations_BaseLangCodes_BaseLangId", column: x => x.BaseLangId, principalTable: "BaseLangCodes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_LangTranslations_LanguageCodes_LangCodeId", column: x => x.LangCodeId, principalTable: "LanguageCodes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AppDynamicNavMenus", columns: table => new { AppId = table.Column<int>(nullable: false), Id = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Class = table.Column<string>(nullable: true), Style = table.Column<string>(nullable: true), Multi = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AppDynamicNavMenus", x => x.AppId); table.ForeignKey( name: "FK_AppDynamicNavMenus_AspNetUsers_AppId", column: x => x.AppId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), UserId = table.Column<int>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<int>(nullable: false), RoleId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<int>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "EmailMessages", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), References = table.Column<List<string>>(nullable: true), MessageFlags = table.Column<List<EmailMessageFlag>>(nullable: true), MessageId = table.Column<string>(nullable: true), Date = table.Column<DateTimeOffset>(nullable: false), Importance = table.Column<int>(nullable: false), Priority = table.Column<int>(nullable: false), Subject = table.Column<string>(nullable: true), Body = table.Column<string>(nullable: true), IsHtml = table.Column<bool>(nullable: false), NeedReadReceipt = table.Column<bool>(nullable: false), NeedDeliveredReceipt = table.Column<bool>(nullable: false), InReplyTo = table.Column<string>(nullable: true), MessageDirection = table.Column<int>(nullable: false), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_EmailMessages", x => x.Id); table.ForeignKey( name: "FK_EmailMessages_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "EmailTemplates", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), ClassDataSource = table.Column<string>(nullable: true), TemplateName = table.Column<string>(nullable: true), Subject = table.Column<string>(nullable: true), Body = table.Column<string>(nullable: true), NeedReadReceipt = table.Column<bool>(nullable: false), NeedDeliveredReceipt = table.Column<bool>(nullable: false), Shared = table.Column<bool>(nullable: false), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_EmailTemplates", x => x.Id); table.ForeignKey( name: "FK_EmailTemplates_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "OldPassword", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), oldPasswordHash = table.Column<string>(nullable: true), UserId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_OldPassword", x => x.id); table.ForeignKey( name: "FK_OldPassword_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PhoneNumber", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), CountryDialCode = table.Column<string>(nullable: false), Number = table.Column<string>(nullable: false), NumberType = table.Column<int>(nullable: false), Notes = table.Column<string>(nullable: true), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PhoneNumber", x => x.Id); table.ForeignKey( name: "FK_PhoneNumber_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserAddress", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), NameId = table.Column<string>(nullable: false), Street = table.Column<string>(nullable: false), Number = table.Column<string>(nullable: false), Flat = table.Column<string>(nullable: true), Staircase = table.Column<string>(nullable: true), City = table.Column<string>(nullable: false), PostalCode = table.Column<string>(nullable: false), County = table.Column<string>(nullable: false), Country = table.Column<int>(nullable: false), State = table.Column<string>(nullable: true), AddressType = table.Column<int>(nullable: false), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserAddress", x => x.Id); table.ForeignKey( name: "FK_UserAddress_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserIdentityNumber", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), IdNumber = table.Column<string>(nullable: false), IdType = table.Column<int>(nullable: false), DocumentCopyUrl = table.Column<string>(nullable: true), DocumentThumbnail = table.Column<string>(nullable: true), IssuingDate = table.Column<DateTime>(nullable: false), ExpiringDate = table.Column<DateTime>(nullable: false), DocumentIssuer = table.Column<string>(nullable: true), IssuingPlace = table.Column<string>(nullable: true), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserIdentityNumber", x => x.Id); table.ForeignKey( name: "FK_UserIdentityNumber_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserMailAddress", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Name = table.Column<string>(nullable: true), Address = table.Column<string>(nullable: false), MailType = table.Column<int>(nullable: false), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserMailAddress", x => x.Id); table.ForeignKey( name: "FK_UserMailAddress_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserProfile", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), UserId = table.Column<int>(nullable: false), LastPageVisited = table.Column<string>(nullable: true), IsNavOpen = table.Column<bool>(nullable: false), IsNavMinified = table.Column<bool>(nullable: false), Count = table.Column<int>(nullable: false), LastUpdatedDate = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserProfile", x => x.Id); table.ForeignKey( name: "FK_UserProfile_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "LangTransPage", columns: table => new { langTranslationId = table.Column<int>(nullable: false), PageId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_LangTransPage", x => new { x.PageId, x.langTranslationId }); table.ForeignKey( name: "FK_LangTransPage_Pages_PageId", column: x => x.PageId, principalTable: "Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_LangTransPage_LangTranslations_langTranslationId", column: x => x.langTranslationId, principalTable: "LangTranslations", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "EmailAdresses", columns: table => new { Id = table.Column<int>(nullable: false), Name = table.Column<string>(nullable: true), Address = table.Column<string>(nullable: true), ToEmailMessageId = table.Column<int>(nullable: false), FromEmailMessageId = table.Column<int>(nullable: false), CcEmailMessageId = table.Column<int>(nullable: false), BccEmailMessageId = table.Column<int>(nullable: false), ReplyEmailMessageId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_EmailAdresses", x => x.Id); table.ForeignKey( name: "FK_EmailAdresses_EmailMessages_BccEmailMessageId", column: x => x.BccEmailMessageId, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EmailAdresses_EmailMessages_CcEmailMessageId", column: x => x.CcEmailMessageId, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EmailAdresses_EmailMessages_FromEmailMessageId", column: x => x.FromEmailMessageId, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EmailAdresses_EmailMessages_Id", column: x => x.Id, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EmailAdresses_EmailMessages_ReplyEmailMessageId", column: x => x.ReplyEmailMessageId, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EmailAdresses_EmailMessages_ToEmailMessageId", column: x => x.ToEmailMessageId, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "EmailHeaders", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Value = table.Column<string>(nullable: true), EmailMessageId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_EmailHeaders", x => x.Id); table.ForeignKey( name: "FK_EmailHeaders_EmailMessages_EmailMessageId", column: x => x.EmailMessageId, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "EmailAttachnemts", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), FileName = table.Column<string>(nullable: true), FileNameUrl = table.Column<string>(nullable: true), FileFullPath = table.Column<string>(nullable: true), FileUrl = table.Column<string>(nullable: true), FileDataBytes = table.Column<byte[]>(nullable: true), TemplateId = table.Column<int>(nullable: false), EmailMessageId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_EmailAttachnemts", x => x.Id); table.ForeignKey( name: "FK_EmailAttachnemts_EmailMessages_EmailMessageId", column: x => x.EmailMessageId, principalTable: "EmailMessages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EmailAttachnemts_EmailTemplates_TemplateId", column: x => x.TemplateId, principalTable: "EmailTemplates", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "NavMenuItems", columns: table => new { AppId = table.Column<int>(nullable: false), Id = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Class = table.Column<string>(nullable: true), Style = table.Column<string>(nullable: true), Href = table.Column<string>(nullable: true), Disabled = table.Column<bool>(nullable: false), AllowSection = table.Column<bool>(nullable: false), Content = table.Column<string>(nullable: true), Icon = table.Column<string>(nullable: true), AppDynamicNavMenuAppId = table.Column<int>(nullable: true), SubMenuListAppId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_NavMenuItems", x => x.AppId); table.ForeignKey( name: "FK_NavMenuItems_AppDynamicNavMenus_AppDynamicNavMenuAppId", column: x => x.AppDynamicNavMenuAppId, principalTable: "AppDynamicNavMenus", principalColumn: "AppId", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "SubMenus", columns: table => new { AppId = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Id = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Class = table.Column<string>(nullable: true), Style = table.Column<string>(nullable: true), Selected = table.Column<bool>(nullable: false), Expanded = table.Column<bool>(nullable: false), AppDynamicNavMenuAppId = table.Column<int>(nullable: true), SubMenuListAppId1 = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_SubMenus", x => x.AppId); table.ForeignKey( name: "FK_SubMenus_AppDynamicNavMenus_AppDynamicNavMenuAppId", column: x => x.AppDynamicNavMenuAppId, principalTable: "AppDynamicNavMenus", principalColumn: "AppId", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "SubMenuHeaders", columns: table => new { AppId = table.Column<int>(nullable: false), Id = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Class = table.Column<string>(nullable: true), Style = table.Column<string>(nullable: true), Content = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_SubMenuHeaders", x => x.AppId); table.ForeignKey( name: "FK_SubMenuHeaders_SubMenus_AppId", column: x => x.AppId, principalTable: "SubMenus", principalColumn: "AppId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "SubMenuLists", columns: table => new { AppId = table.Column<int>(nullable: false), Id = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Class = table.Column<string>(nullable: true), Style = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_SubMenuLists", x => x.AppId); table.ForeignKey( name: "FK_SubMenuLists_SubMenus_AppId", column: x => x.AppId, principalTable: "SubMenus", principalColumn: "AppId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_LanguageId", table: "AspNetUsers", column: "LanguageId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); migrationBuilder.CreateIndex( name: "IX_EmailAdresses_BccEmailMessageId", table: "EmailAdresses", column: "BccEmailMessageId"); migrationBuilder.CreateIndex( name: "IX_EmailAdresses_CcEmailMessageId", table: "EmailAdresses", column: "CcEmailMessageId"); migrationBuilder.CreateIndex( name: "IX_EmailAdresses_FromEmailMessageId", table: "EmailAdresses", column: "FromEmailMessageId"); migrationBuilder.CreateIndex( name: "IX_EmailAdresses_ReplyEmailMessageId", table: "EmailAdresses", column: "ReplyEmailMessageId"); migrationBuilder.CreateIndex( name: "IX_EmailAdresses_ToEmailMessageId", table: "EmailAdresses", column: "ToEmailMessageId"); migrationBuilder.CreateIndex( name: "IX_EmailAttachnemts_EmailMessageId", table: "EmailAttachnemts", column: "EmailMessageId"); migrationBuilder.CreateIndex( name: "IX_EmailAttachnemts_TemplateId", table: "EmailAttachnemts", column: "TemplateId"); migrationBuilder.CreateIndex( name: "IX_EmailHeaders_EmailMessageId", table: "EmailHeaders", column: "EmailMessageId"); migrationBuilder.CreateIndex( name: "IX_EmailMessages_UserId", table: "EmailMessages", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_EmailTemplates_UserId", table: "EmailTemplates", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_LangTranslations_BaseLangId", table: "LangTranslations", column: "BaseLangId"); migrationBuilder.CreateIndex( name: "IX_LangTranslations_LangCodeId", table: "LangTranslations", column: "LangCodeId"); migrationBuilder.CreateIndex( name: "IX_LangTransPage_langTranslationId", table: "LangTransPage", column: "langTranslationId"); migrationBuilder.CreateIndex( name: "IX_NavMenuItems_AppDynamicNavMenuAppId", table: "NavMenuItems", column: "AppDynamicNavMenuAppId"); migrationBuilder.CreateIndex( name: "IX_NavMenuItems_SubMenuListAppId", table: "NavMenuItems", column: "SubMenuListAppId"); migrationBuilder.CreateIndex( name: "IX_OldPassword_UserId", table: "OldPassword", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_PhoneNumber_UserId", table: "PhoneNumber", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_SubMenus_AppDynamicNavMenuAppId", table: "SubMenus", column: "AppDynamicNavMenuAppId"); migrationBuilder.CreateIndex( name: "IX_SubMenus_SubMenuListAppId1", table: "SubMenus", column: "SubMenuListAppId1"); migrationBuilder.CreateIndex( name: "IX_UserAddress_UserId", table: "UserAddress", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_UserIdentityNumber_UserId", table: "UserIdentityNumber", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_UserMailAddress_UserId", table: "UserMailAddress", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_UserProfile_UserId", table: "UserProfile", column: "UserId", unique: true); migrationBuilder.AddForeignKey( name: "FK_NavMenuItems_SubMenuHeaders_AppId", table: "NavMenuItems", column: "AppId", principalTable: "SubMenuHeaders", principalColumn: "AppId", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_NavMenuItems_SubMenuLists_SubMenuListAppId", table: "NavMenuItems", column: "SubMenuListAppId", principalTable: "SubMenuLists", principalColumn: "AppId", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_SubMenus_SubMenuLists_SubMenuListAppId1", table: "SubMenus", column: "SubMenuListAppId1", principalTable: "SubMenuLists", principalColumn: "AppId", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_AppDynamicNavMenus_AspNetUsers_AppId", table: "AppDynamicNavMenus"); migrationBuilder.DropForeignKey( name: "FK_SubMenus_AppDynamicNavMenus_AppDynamicNavMenuAppId", table: "SubMenus"); migrationBuilder.DropForeignKey( name: "FK_SubMenus_SubMenuLists_SubMenuListAppId1", table: "SubMenus"); migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "EmailAdresses"); migrationBuilder.DropTable( name: "EmailAttachnemts"); migrationBuilder.DropTable( name: "EmailHeaders"); migrationBuilder.DropTable( name: "LangTransPage"); migrationBuilder.DropTable( name: "NavMenuItems"); migrationBuilder.DropTable( name: "OldPassword"); migrationBuilder.DropTable( name: "PhoneNumber"); migrationBuilder.DropTable( name: "UserAddress"); migrationBuilder.DropTable( name: "UserIdentityNumber"); migrationBuilder.DropTable( name: "UserMailAddress"); migrationBuilder.DropTable( name: "UserProfile"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "EmailTemplates"); migrationBuilder.DropTable( name: "EmailMessages"); migrationBuilder.DropTable( name: "Pages"); migrationBuilder.DropTable( name: "LangTranslations"); migrationBuilder.DropTable( name: "SubMenuHeaders"); migrationBuilder.DropTable( name: "BaseLangCodes"); migrationBuilder.DropTable( name: "AspNetUsers"); migrationBuilder.DropTable( name: "LanguageCodes"); migrationBuilder.DropTable( name: "AppDynamicNavMenus"); migrationBuilder.DropTable( name: "SubMenuLists"); migrationBuilder.DropTable( name: "SubMenus"); } } }
some tip ?
Thank you in advance
How to sanitize inputs for Html.Raw on server side
I have several views where I use @Html.Raw and would like to sanitize rich text inputs. Possibly what the Rich Text Box may emit and take a white list type of approach to the tags/attributes that the server-side will accept. I'm not sure how to do this or where to look to do this.
@foreach (var dorItem in catGroup) {<tr><td class="view-dor">@Html.Raw(dorItem.Responsibility)</td><td class="view-dor-description">@Html.Raw(dorItem.Description)<div class="verticalspace"></div> @foreach (var dorResponse in dorItem.DorItemResponses) {<div style=" border: solid black 1px; background-color: #eeeeee;"><b>@dorResponse.Date.ToString("MM/dd/yyyy") @dorResponse.Title</b><div class="verticalspace"></div>@Html.Raw(dorResponse.Response)</div> }</td> @if (@dorItem.Status.Color.Name == "Yellow") {<td class="view-dor"><font class="dor-status-dark" color="@dorItem.Status.Color.Name"><b>@dorItem.Status.Name</b></font></td> } else {<td class="view-dor"><font color="@dorItem.Status.Color.Name"><b>@dorItem.Status.Name</b></font></td> }</tr> }
How to get a photo image to show via Controller
In my controller I am trying to get the photo image but it doesn't come across on the view. I feel like the problem is with the code in the controller. What am I missing?
Controller:
public async Task<ActionResult> GetPhoto(long photoId, CancellationToken cancellationToken) { try { var photoFile = await _photoService.GetPhotoByPhotoIdAsync(photoId, cancellationToken) .ConfigureAwait(false); var image = photoFile.Image; if (photoFile == null || photoFile.Id < 1) { return NotFound(); } Response.Headers.Add("content-disposition", "inline;filename=" + photoFile); return File(image, "png"); } catch { return NotFound(); } }
View:
<div class="col-md-4"><div class="profile-img"> @{ if (Model.PhotoId != null) { <img src="@Url.Action("GetPhoto", "Photo", new {photoId = Model.PhotoId})" class="user" style="width: 150px; height: 150px;" alt="profile pic"/> } else {<div class="user egghead"></div> } }</div></div>
Dynamic routing problem
I'm developing a multilingual website. I read menus from db
E.g : Contact - en
Kommunikation - de
I have contactController.cs
[Route(“{LangCode}/contact”)]
[Route(“{LangCode}/kammunikation”)]
..............Task Index()
return View()
I dont want this usage.
If i have 5 language, I read menu names from table
And create dynamic routes and redirect contactconroller
I use .net core 2.2
Optimisation of Reverse Proxy
Hi guys,
So I am currently working on implementing a new project I am using MVC .NET Core 3.1 to do all of my developments.
I have a requirement to create a reverse proxy which all of my client side applications will connect to. The one I am having the biggest issue with is a connection to an on premise Analysis Services Instance, because the response content can get quite large it results in slow response times for my client.
Here is the code that I have:
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace SSASProxyTest2 { public class ReverseProxyMiddleware { private static readonly HttpClient _httpClient = new HttpClient(); private readonly RequestDelegate _nextMiddleware; public ReverseProxyMiddleware(RequestDelegate nextMiddleware) { _nextMiddleware = nextMiddleware; } public async Task Invoke(HttpContext context) { var targetUri = BuildTargetUri(context.Request); if (targetUri != null) { var targetRequestMessage = CreateTargetMessage(context, targetUri); using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted)) { context.Response.StatusCode = (int)responseMessage.StatusCode; CopyFromTargetResponseHeaders(context, responseMessage); await responseMessage.Content.CopyToAsync(context.Response.Body); } return; } await _nextMiddleware(context); } private HttpRequestMessage CreateTargetMessage(HttpContext context, Uri targetUri) { var requestMessage = new HttpRequestMessage(); CopyFromOriginalRequestContentAndHeaders(context, requestMessage); String username = "username"; String password = "password"; String encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); requestMessage.Headers.Add("Authorization", "Basic " + encoded); requestMessage.RequestUri = targetUri; requestMessage.Headers.Host = targetUri.Host; requestMessage.Method = GetMethod(context.Request.Method); return requestMessage; } private void CopyFromOriginalRequestContentAndHeaders(HttpContext context, HttpRequestMessage requestMessage) { var requestMethod = context.Request.Method; if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod)) { var streamContent = new StreamContent(context.Request.Body); requestMessage.Content = streamContent; } foreach (var header in context.Request.Headers) { requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()); } } private void CopyFromTargetResponseHeaders(HttpContext context, HttpResponseMessage responseMessage) { foreach (var header in responseMessage.Headers) { context.Response.Headers[header.Key] = header.Value.ToArray(); } foreach (var header in responseMessage.Content.Headers) { context.Response.Headers[header.Key] = header.Value.ToArray(); } context.Response.Headers.Remove("transfer-encoding"); } private static HttpMethod GetMethod(string method) { if (HttpMethods.IsDelete(method)) return HttpMethod.Delete; if (HttpMethods.IsGet(method)) return HttpMethod.Get; if (HttpMethods.IsHead(method)) return HttpMethod.Head; if (HttpMethods.IsOptions(method)) return HttpMethod.Options; if (HttpMethods.IsPost(method)) return HttpMethod.Post; if (HttpMethods.IsPut(method)) return HttpMethod.Put; if (HttpMethods.IsTrace(method)) return HttpMethod.Trace; return new HttpMethod(method); } private Uri BuildTargetUri(HttpRequest request) { Uri targetUri = new Uri("https://Example.com/msmdpump.dll"); return targetUri; } } }
As you can see I am taking the original request changing the target, adding credentials then returning the response.
This is where the block seems to be on large requests:
await responseMessage.Content.CopyToAsync(context.Response.Body);
This is going to be MiddelWare in my application. For completeness my startupclass has this:
app.Map("/api/test", api => { api.UseMiddleware<ReverseProxyMiddleware>(); });
Can anyone tell me if this can be optimised further to deal with large responses?
Really appreciate any help.
Joe
Can't Run my app has IIS Express
Ok so I did some settings when trying to deploy asp.net core web app locally sometimes ago. Suddenly i just noticed that on vs when I try to run my app.
I can not run app with the IIS Express option. I have to pick the the name of the app when I want to debug.
https://pasteboard.co/J54l9V9.jpg check that link for a snapshot so you understand what am saying
This is a snapshot of my vS to explain the problem. Please this is a problem for me. Cos if I have multiple website on my solution I I cant run every thing at once.
How do I fix this problem. Got a problem with multiple sites and I need to run every thing at once so I can monitor all from IIS instance cos they all depend on each other to work well.
Sending emails from a .NET API and Angular project
I'm learning to code by developing a project that uses Angular and .NET core for an API. I'm starting into a new area of this project that I'm hoping to get a little advice on as it a new area to me, and thats sending emails from the project.
There are 2 factions to the project:
A: Sending platform emails (IE: Registration emails, password resets, stuff the user requests from the Angular project)
B: Automatic reporting emails that contain data submitted to the project via a mobile app through the API.
For the platform emails, I understand this needs to be done in the Angular project itself. However, when someone submits data via the API with the use of a phone based app, an email should be sent to a designated person containing the data that was submitted. This last part is where I'm running into troubles figuring out what needs to be done.
I'm going to incorporate SendGrid into the project to handle all of the emails. However, what is the best practice to send the emails to the designated person when info is passed via a mobile app through the API? I'm going to assume this would be built in the API itself as it wouldn't be a user triggered event in the Angular project. In fact, the Angular project wouldn't even be aware that the data had been submitted.
Any advice on how I would tackle this? Would I build a trigger within the API that is tripped when the data is submitted that tells Sendgrid to send the email with the data? Would this be built within the .NET API? And how does one build an email template using just C#?
Thanks in advance for any input provided!
Help needed in Passing a method in Typeof()
Hi,
I am using swagger for my asp.net core 2.2 documentation and for displaying the response model, i have to use[ProducesResponseType(typeof(ResponseObject), 200)].
In my case, i am not directly returning the Response object. I have a static method which takes the output object as paramater and constructs the ResponseObject. Details Below,
//Model.cs Public class UserResponse { public int UserId { get; set; } public string UserMessage{ get; set; } } //Controller.cs [Consumes("application/json")] [ProducesResponseType(typeof(APIResponse), 200)] public IActionResult GetUser(string UserName) { UserResponse userResponse = dbService.GetUser(UserName); if(userResponse.UserId > 0) { return Ok(Utility.ConstructResponse(userResponse , Utility.ConstructMessage(1000, "Success")); } }
public static class Utility { public static APIResponse ConstructResponse(object objResult,Message message) { APIResponse baseResponse = new APIResponse(); TResponse tResponse = new TResponse(System.Net.HttpStatusCode.OK); tResponse.TMessage = message; tResponse.Result = objResult; baseResponse.TResponse = tResponse; return baseResponse; } public static Message ConstructMessage(short Code, string Description) { return new Message { Code = Code, Description = Description }; } }
So,if i use [ProducesResponseType(typeof(APIResponse), 200)] i am getting the model on the swagger when i lunch the api documentation, The Result object is empty as follows
{"TResponse": {"Version": "string","StatusCode": "Continue","Result": {},"TMessage": {"Code": 0,"Description": "string" } } }
<div> </div> <div>Expected Sample output Response Should be </div>
{"TResponse": {"Version": "string","StatusCode": "Continue","Result": {"UserId": 0,"UserMessage": "string" },"TMessage": {"Code": 0,"Description": "string" } } }
I am not sure how to pass the method in typeof(). Any suggestion how to make the url response like this in the swagger documentation. Any help will be highly appreciated.
Help Needed in Transaction
<div>Hello,</div> <div> </div> <div>I am using asp.net core 2.2 and i would need to use thetransaction scope. on my business layer i am using transaction scope as follows</div> <div>
TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = new TimeSpan(0, 10, 0); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { // Method 1 which has DB connnection am opening and coling the connection properly // Method 2 which has DB connnection am opening and coling the connection properly // Method 3 which has DB connnection am opening and coling the connection properly scope.Complete(); }
DAL Layer :</div> <div></div> <div>
public class EmpDB : DbContext { public EmpDB() { } public EmpDB(DbContextOptions<EmpDB> options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(//ConnectionString); } } public int GetEmpId(string EmpEmail) { using (EmpDB empDB = new EmpDB()) { using (var dbCommand = empDB.Database.GetDbConnection().CreateCommand()) { // proc call with parameters if (dbCommand.Connection.State != ConnectionState.Open) { dbCommand.Connection.Open(); } int EmpId = (int)dbCommand.ExecuteScalar(); dbCommand.Connection.Close(); return EmpId } } }
when i run the API, am getting the below error</div> <div></div> <div>
System.PlatformNotSupportedException: This platform does not support distributed transactions. at System.Transactions.Distributed.DistributedTransactionManager.GetDistributedTransactionFromTransmitterPropagationToken(Byte[] propagationToken) at System.Transactions.TransactionInterop.GetDistributedTransactionFromTransmitterPropagationToken(Byte[] propagationToken) at System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction tx) at System.Transactions.TransactionStateDelegatedBase.EnterState(InternalTransaction tx) at System.Transactions.EnlistableStates.Promote(InternalTransaction tx) at System.Transactions.Transaction.Promote() at System.Transactions.TransactionInterop.ConvertToDistributedTransaction(Transaction transaction) at System.Transactions.TransactionInterop.GetExportCookie(Transaction transaction, Byte[] whereabouts) at System.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transaction transaction, Byte[] whereAbouts) at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx) at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open()
am no sure what mistake am doing??? please help me to solve this error. i tried to google through and people are saying .net core 2.2 supports transaction scope. pleasesuggest to solve the issue</div> <div></div>
Can i host asp.net in this platform.
Hi guys I recently started asp.net core development and now I'm finished and ready to launch my first website but I'm really confused about which hosting plan to buy. I found this hosting plan under my budget, not sure but I think it isLinux based, can you please tell me if I can host my asp.net core website here or not.
Link to site - https://www.hostinger.in/web-hosting
Also, I'm using ef core latest version and using SQL Server LocalDB.
I was thinking to buy the "premium web hosting" plan can you check this site and tell me whether I will be able to host here not.
Why my website can not works in IIS of Windows Server 2019?
I have a website made by asp.net core 3.1.
It is the first time I publish it on Windows server 2019 Datacenter 1809(17763.1158).
However, it doesn't work but the IE reports ''Can’t reach this page' error on the page.
I run the .exe file in the directory of the project on the server computer. It starts a command-line and showed these:
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\Project
I access the http://localhost:5000. All works well now.
I have not only ensured set the .NET CLR version to No Managed Code but also ensured there is an AspNetCoreModuleV2 in the module.
I doubt whether it is the problem of DNS or URL. After I set the Host Name to null to make the website only works locally, it still no works.
What's wrong with it? How can I solve this? Thank you.
---------------------------------
PS: Here is some information with dotnet --info of the server computer
Microsoft Windows [Version 10.0.17763.1158]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\Administrator>dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.1.201
Commit: b1768b4ae7
Runtime Environment:
OS Name: Windows
OS Version: 10.0.17763
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\3.1.201\
Host (useful for support):
Version: 3.1.3
Commit: 4a9f85e9f8
.NET Core SDKs installed:
3.1.201 [C:\Program Files\dotnet\sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
C:\Users\Administrator>
can i put cors into a mediator pipelinebehaviour?
Hi
I need to add cors to my public api, and i needto allow it to be dynamic, eg adding new ui's through an API, so hard coding it into the startup file isn't an options
Is there any reason i should build my own authentication and add it to a pipeline bahaviour?
and is there anything i need to take into consideration