Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

ASP.NET MVC – example of RequiredRouteConstraint (:required) use

$
0
0

I am not sure about RequiredRouteConstraint use. The definition sais“Constraints a route parameter that must have a value.” and”This constraint is primarily used to enforce that a non-parameter value is present during URL generation.”.

The route normally without parameter specified would not be matched if it is not optional parameter or if the default route not comply this case. So appending:required constraint to route parameter (e.g. {name:required}) seems useless to me.

How does look like example of RequiredRouteConstraint common use?


Getting User Info - windows authentication

$
0
0

Hi,

I am using ASP.Net Core and Entity Framework 6.0.

I am trying to get the windows user info, which will be checked against the application database for authorization access.

I am having problems with the following script:

BaseController.cs

public class BaseController: Controller
{

     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
            if (HttpContext.User == null || HttpContext.User.Identity.AuthenticationType != "Forms") 
            {
                    //return null; 
             }

             var identity = HttpContext.User.Identity;
      }
}


web.config

<configuration>
  <system.web>
    <authentication mode="Windows" />
    <authorization>
       <deny users="?"/>
    </authorization>
  </system.web>
</configuration>

When I run the application,

HttpContext.User.Identity.AuthenticationType = "" and HttpContext.User.Identity = "".  How can I get the current windows username?

Thanks,

tinac99

ASP.NET Core (1.1) web application behaving differently depending on target framework.

$
0
0

I have an ASP.NET Core 1.1 web application (simple web API) and an Angular client application. I'm using Azure Active Directory B2C as my auth provider and I've deployed my applications to three separate Azure Web Apps using VS2017 publishing.

  1. Client - Angular client
  2. ApiCore - The ASP.NET Core 1.1 web application published with the TargetFramework netcoreapp1.1
  3. ApiFramework - The ASP.NET Core 1.1 web application published with the TargetFramework net462

Client has a simple config that allows me to change the URI for its API service making it easy to toggle between CoreApi and FrameworkApi backing services.

If the Client's API URI is set to ApiCore's URI everything is working beautifully. Users have access to both secure and open resource when logged in and receive 401 accessing secure resources if not. However, setting the Client's API URI to the ApiFramework URI causes the user to receive 401 accessing secured resources regardless of login status. Open resources continue to function normally.

To be clear the only difference in the publishing of these two web applications is the value of the TargetFramework element in the .csproj file. The code and all configuration is identical.

The following is my .csproj file contents. I simply change the commented TargetFramework line and deploy using VS2017 publishing where I have a profile for each target (shown is for the ApiCore publish).

<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><TargetFramework>netcoreapp1.1</TargetFramework><!--<TargetFramework>net462</TargetFramework>--></PropertyGroup><ItemGroup><DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" /></ItemGroup><ItemGroup><PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" /><PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Authentication" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="1.1.1" /></ItemGroup><ItemGroup Condition=" '$(TargetFramework)' == 'net462' "><Reference Include="System" /><Reference Include="Microsoft.CSharp" /></ItemGroup></Project>

ASP.NET Core routing works in VS IIS Express but not in IIS 10

$
0
0

I am developing ASP.NET Core web api. here i have a situation like i have to use multiple get functions which get data from sql server db. So for that i'm doing custom attribute routes. below are my codes

[Route("api/[controller]")]
public class MeController : Controller
{
    private readonly ITechRepository _tech;
    private readonly IPageOptions _page;
    public MeController(ITechRepository tech,IPageOptions page)
    {
        _tech = tech;
        _page = page;
    }

   [Route("getTech")]
    public IEnumerable<TechStack> Get()
    {
        return _tech.getAll();
    }
    [Route("getOptions")]
    public IEnumerable<PageControl> getOptions()
    {
        return _page.getOptions();
    }
     //GET api/values/5
    [HttpGet("{id}")]
    public int Get(int id)
    {
        return id;
    }
}

The above routes are works well in VS IIS Express and this is that url http://localhost:51889/api/me/gettech

But when i publish this api in IIS 10. The getTech and getOptions were not working it producing 404 error and also [HttpGet("{id}")] is working in both.

Can anybody help on this...

Asp.Net Core 1.1 Dropdown issues

$
0
0

Hello,

   I am having two issues with the Select tag helper in my project.  In both the Edit and Create views the validation for the Select tag helper is not working.  Also the view is not setting to the selected option, as it seems to be stripping it away when displaying the view.  Each view has multiple select tag helpers, pulling data from multiple tables.

So here is my controller for both the Create and Edit. 

        private readonly LotroModel _db;               public CharactersController(LotroModel db)        {            _db = db;        }
        public IActionResult Create()        {            var serverList = _db.Database.SqlQuery<ServersNamesListViewModel>("SELECT Server_ID AS ServerID, Server_Name AS ServerName FROM dbo.Server").ToList();            var professionList = _db.Database.SqlQuery<ProfessionNamesListViewModel>("SELECT Profession_ID AS ProfessionID, Profession_Name AS ProfessionName FROM dbo.Profession").ToList();            var levelList = _db.Database.SqlQuery<LevelNumbersListViewModel>("SELECT Level_ID AS LevelID, Level_Number AS LevelNumber FROM dbo.Level").ToList();            var classList = _db.Database.SqlQuery<ClassNamesListViewModel>("SELECT Class_ID AS ClassID, Class_Name AS ClassName FROM dbo.Class").ToList();            var raceList = _db.Database.SqlQuery<RaceNamesListViewModel>("SELECT Race_ID AS RaceID, Race_Name AS RaceName FROM dbo.Race").ToList();            var sList = new List<SelectListItem>();            var pList = new List<SelectListItem>();            var lList = new List<SelectListItem>();            var cList = new List<SelectListItem>();            var rList = new List<SelectListItem>();            foreach( ServersNamesListViewModel sn in serverList )            {                sList.Add(new SelectListItem { Text = sn.ServerName, Value = sn.ServerID.ToString() });            }            foreach( ProfessionNamesListViewModel pn in professionList )            {                pList.Add(new SelectListItem { Text = pn.ProfessionName, Value = pn.ProfessionID.ToString() });            }            foreach( LevelNumbersListViewModel ln in levelList )            {                lList.Add(new SelectListItem { Text = ln.LevelNumber.ToString(), Value = ln.LevelID.ToString() });            }            foreach( ClassNamesListViewModel cn in classList )            {                cList.Add(new SelectListItem { Text = cn.ClassName, Value = cn.ClassID.ToString() });            }            foreach( RaceNamesListViewModel rn in raceList)            {                rList.Add(new SelectListItem { Text = rn.RaceName, Value = rn.RaceID.ToString() });            }            var character = new CharacterViewModel()            {                ServersList = sList,                ProfessionList = pList,                LevelList = lList,                ClassList = cList,                RaceList = rList            };            return View(character);        }        // POST: Characters/Create        // To protect from overposting attacks, please enable the specific properties you want to bind to, for        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.        [HttpPost]        [ValidateAntiForgeryToken]        public async Task<IActionResult> Create( CharacterViewModel returnedView, Character character)        {            if (ModelState.IsValid)            {                character.Char_First_Name = returnedView.Char_First_Name;                character.Char_Last_Name = returnedView.Char_Last_Name;                character.Char_Gender = returnedView.Char_Gender;                character.ServerServer_ID = Convert.ToInt32(returnedView.ServersList.Select(x => x.Value));                character.Profession_Profession_ID = Convert.ToInt32(returnedView.ProfessionList.Select(x => x.Value));                character.Level_Level_ID = Convert.ToInt32(returnedView.LevelList.Select(x => x.Value));                character.Class_Class_ID = Convert.ToInt32(returnedView.ClassList.Select(x => x.Value));                character.Race_Race_ID = Convert.ToInt32(returnedView.RaceList.Select(x => x.Value));                _db.Characters.Add(character);                await _db.SaveChangesAsync();                return RedirectToAction("Menu", "Menu");            }                       //This is not returning the dropdowns, need the returnView values as selected.                          return View(returnedView);        }        public async Task<IActionResult> Edit(int? id)        {            if(id == null)            {                return BadRequest();            }            Character character = await _db.Characters.FindAsync(id);            if(character == null)            {                return NotFound();            }            var serverList = _db.Database.SqlQuery<ServersNamesListViewModel>(sql: "SELECT Server_ID AS ServerID, Server_Name AS ServerName, CAST( CASE WHEN Server_ID IN(SELECT ServerServer_ID FROM Character WHERE Char_ID = @p0) THEN 1 ELSE 0 END AS Bit) AS IsSelected FROM dbo.Server", parameters: new object[] { id }).ToList();            var professionList = _db.Database.SqlQuery<ProfessionNamesListViewModel>(sql: "SELECT Profession_ID AS ProfessionID, Profession_Name AS ProfessionName, CAST(CASE WHEN Profession_ID IN (SELECT Profession_Profession_ID FROM Character WHERE Char_ID = @p0) THEN 1 ELSE 0 END AS Bit) AS IsSelected FROM dbo.Profession", parameters: new object[] { id }).ToList();            var levelList = _db.Database.SqlQuery<LevelNumbersListViewModel>(sql: "SELECT Level_ID AS LevelID, Level_Number AS LevelNumber, CAST(CASE WHEN Level_ID IN (SELECT Level_Level_ID FROM Character WHERE Char_ID = @p0) THEN 1 ELSE 0 END AS Bit) AS IsSelected FROM dbo.Level", parameters: new object[] { id }).ToList();            var classList = _db.Database.SqlQuery<ClassNamesListViewModel>(sql: "SELECT Class_ID AS ClassID, Class_Name AS ClassName, CAST(CASE WHEN Class_ID IN (SELECT Class_Class_ID FROM Character WHERE Char_ID = @p0) THEN 1 ELSE 0 END AS Bit) AS IsSelected FROM dbo.Class", parameters: new object[] { id }).ToList();            var raceList = _db.Database.SqlQuery<RaceNamesListViewModel>(sql: "SELECT Race_ID AS RaceID, Race_Name AS RaceName, CAST(CASE WHEN Race_ID IN (SELECT Race_Race_ID FROM Character WHERE Char_ID = @p0) THEN 1 ELSE 0 END AS Bit) AS IsSelected FROM dbo.Race", parameters: new object[] { id }).ToList();            var sList = new List<SelectListItem>();            var pList = new List<SelectListItem>();            var lList = new List<SelectListItem>();            var cList = new List<SelectListItem>();            var rList = new List<SelectListItem>();            foreach (ServersNamesListViewModel sn in serverList)            {                sList.Add(new SelectListItem { Text = sn.ServerName, Value = sn.ServerID.ToString(), Selected = sn.IsSelected });            }            foreach (ProfessionNamesListViewModel pn in professionList)            {                pList.Add(new SelectListItem { Text = pn.ProfessionName, Value = pn.ProfessionID.ToString(), Selected = pn.IsSelected });            }            foreach (LevelNumbersListViewModel ln in levelList)            {                lList.Add(new SelectListItem { Text = ln.LevelNumber.ToString(), Value = ln.LevelID.ToString(), Selected = ln.IsSelected });            }            foreach (ClassNamesListViewModel cn in classList)            {                cList.Add(new SelectListItem { Text = cn.ClassName, Value = cn.ClassID.ToString(), Selected = Selected = cn.IsSelected });            }            foreach (RaceNamesListViewModel rn in raceList)            {                rList.Add(new SelectListItem { Text = rn.RaceName, Value = rn.RaceID.ToString(), Selected = Selected = rn.IsSelected });            }            var eCharacter = new CharacterViewModel();            eCharacter.CharID = character.Char_ID;            eCharacter.Char_First_Name = character.Char_First_Name;            eCharacter.Char_Last_Name = character.Char_Last_Name;            eCharacter.Char_Gender = character.Char_Gender;            eCharacter.ServersList = sList;            eCharacter.ProfessionList = pList;            eCharacter.LevelList = lList;            eCharacter.ClassList = cList;            eCharacter.RaceList = rList;            return View(eCharacter);        }

Here is the View Model I am working with, plus a view model for the selectlistitem, all the selectlistitem view models are relatively the same, with just a change of data.

public class CharacterViewModel    {        [HiddenInput]        public int CharID { get; set; }        [Required]        [StringLength(20)]        [Display(Name = "First Name")]        public string Char_First_Name { get; set; }        [StringLength(20)]        [Display(Name = "Last Name")]        public string Char_Last_Name { get; set; }        [Required]        [StringLength(7)]        [Display(Name = "Gender")]        public string Char_Gender { get; set; }        [Required]        [Display(Name = "Server")]        public List<SelectListItem> ServersList { get; set; }        [Display(Name = "Profession")]        public List<SelectListItem> ProfessionList { get; set; }        [Required]        [Display(Name = "Level")]        public List<SelectListItem> LevelList { get; set; }        [Required]        [Display(Name = "Class")]        public List<SelectListItem> ClassList { get; set; }        [Required]        [Display(Name = "Race")]        public List<SelectListItem> RaceList { get; set; }    }

public class ServersNamesListViewModel    {        [Key]        public int ServerID { get; set; }        [Required]        [Display(Name = "Server Name")]        public string ServerName { get; set; }
public bool IsSelected { get; set; }    }

Lastly here are the two views, with the global portion of my javascript:

@*    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@model Lotro.WebAppMVC.Models.CharacterViewModels.CharacterViewModel
@{    ViewBag.Title = "Create";    Layout = "~/Views/Shared/_CharAddLayout.cshtml";
}<h2 style="font-family:'Times New Roman', Times, serif; text-align:center; color:white">The Lord of the Rings Online Character Database</h2><form asp-controller="Characters" asp-action="Create" method="post">    <div class="form-horizontal">        <h4 style="font-family:'Times New Roman', Times, serif; text-align:center; color:white">Character Addition</h4>        <hr />        <div asp-validation-summary="All" class="text-danger"></div>        @*This is not doing validation correctly for the dropdowns.  Might need a javascript to say if value = -- then not valid.*@        <div class="form-group">            <label asp-for="Char_First_Name" class="control-label col-md-2"></label>            <div class="col-md-10">                <input asp-for="Char_First_Name" class="form-control" />            </div>        </div>        <div class="form-group">            <label asp-for="Char_Last_Name" class="control-label col-md-2"></label>            <div class="col-md-10">                <input asp-for="Char_Last_Name" class="form-control" />            </div>        </div>        <div class="form-group">            <label asp-for="Char_Gender" class="control-label col-md-2"></label>            <div class="col-md-10">                <input asp-for="Char_Gender" class="form-control" />            </div>        </div>        <div class="form-group">            <label asp-for="ServersList" class="control-label col-md-2"></label>            <div class="col-md-10">                <select class="form-control single-select" asp-for="ServersList" asp-items="@Model.ServersList">                    <option selected value="--">Select a Server</option>                </select>            </div>        </div>        <div class="form-group">            <label asp-for="ProfessionList" class="control-label col-md-2"></label>            <div class="col-md-10">                <select class="form-control single-select" asp-for="ProfessionList" asp-items="@Model.ProfessionList">                    <option selected value="--">Select a Profession</option>                </select>            </div>        </div>        <div class="form-group">            <label asp-for="LevelList" class="control-label col-md-2"></label>            <div class="col-md-10">                <select class="form-control single-select" asp-for="LevelList" asp-items="@Model.LevelList">                    <option selected value="--">Select a Level</option>                </select>            </div>        </div>        <div class="form-group">            <label asp-for="ClassList" class="control-label col-md-2"></label>            <div class="col-md-10">                <select class="form-control single-select" asp-for="ClassList" asp-items="@Model.ClassList">                    <option selected value="--">Select a Class</option>                </select>            </div>        </div>        <div class="form-group">            <label asp-for="RaceList" class="control-label col-md-2"></label>            <div class="col-md-10">                <select class="form-control single-select" asp-for="RaceList" asp-items="@Model.RaceList">                    <option selected value="--">Select a Race</option>                </select>            </div>        </div>        <div class="form-group">            <div class="col-md-offset-2 col-md-10">                <div class="col-md-1">                    <input type="submit" value="Create" class="btn btn-default" />                </div>                <div class="col-md-1"></div>                <div class="col-md-2">                    <a asp-controller="Menu" , asp-action="Menu" , null, class="btn btn-danger col-md-push-3">Cancel</a>                </div>                          </div>        </div>    </div></form>

@*    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@model Lotro.WebAppMVC.Models.CharacterViewModels.CharacterViewModel
@{    ViewBag.Title = "Edit";    Layout = "~/Views/Shared/_CharEdLayout.cshtml";
}<h2 style="font-family:'Times New Roman', Times, serif; text-align:center; color:white">The Lord of the Rings Online Character Database</h2><form asp-controller="Characters" asp-action="Edit" method="post">    <div class="form-horizontal">        <h4 style="font-family:'Times New Roman', Times, serif; text-align:center; color:white">Edit Character</h4>        <hr />        <div asp-validation-summary="All" class="text-danger"></div>        <input asp-for="@Model.CharID" />    </div>    <div class="form-group">        <label asp-for="Char_First_Name" class="control-label col-md-2"></label>        <div class="col-md-10">            <input asp-for="Char_First_Name" class="form-control" />        </div>    </div>    <div class="form-group">        <label asp-for="Char_Last_Name" class="control-label col-md-2"></label>        <div class="col-md-10">            <input asp-for="Char_Last_Name" class="form-control" />        </div>    </div>    <div class="form-group">        <label asp-for="Char_Gender" class="control-label col-md-2"></label>        <div class="col-md-10">            <input asp-for="Char_Gender" class="form-control" />        </div>    </div>    <div class="form-group">        <label asp-for="ServersList" class="control-label col-md-2"></label>        <div class="col-md-10">            <select class="form-control single-select" asp-for="ServersList" asp-items="@Model.ServersList">                <option value="--">Select a Server</option>            </select>        </div>    </div>    <div class="form-group">        <label asp-for="ProfessionList" class="control-label col-md-2"></label>        <div class="col-md-10">            <select class="form-control single-select" asp-for="ProfessionList" asp-items="@Model.ProfessionList">                <option value="--">Select a Profession</option>            </select>        </div>    </div>    <div class="form-group">        <label asp-for="LevelList" class="control-label col-md-2"></label>        <div class="col-md-10">            <select class="form-control single-select" asp-for="LevelList" asp-items="@Model.LevelList">                <option value="--">Select a Level</option>            </select>        </div>    </div>    <div class="form-group">        <label asp-for="ClassList" class="control-label col-md-2"></label>        <div class="col-md-10">            <select class="form-control single-select" asp-for="ClassList" asp-items="@Model.ClassList">                <option value="--">Select a Class</option>            </select>        </div>    </div>    <div class="form-group">        <label asp-for="RaceList" class="control-label col-md-2"></label>        <div class="col-md-10">            <select class="form-control single-select" asp-for="RaceList" asp-items="@Model.RaceList">                <option value="--">Select a Race</option>            </select>        </div>    </div>    <div class="form-group">        <div class="col-md-offset-2 col-md-10">            <div class="col-md-1">                <input type="submit" value="Create" class="btn btn-default" />            </div>            <div class="col-md-1"></div>            <div class="col-md-2">                <a asp-controller="Menu" , asp-action="EdChar" , null, class="btn btn-danger col-md-push-3">Cancel</a>            </div>        </div>    </div></form>

$(function () {    $(".single-select").removeAttr("multiple");
});

What I see in the development tools for the web browsers is essentially the same, no errors show in the console.  I am getting 200 OKs in the network section, but in my DOM, I see:

<div class="col-md-10">            <select name="ServersList" class="form-control single-select" id="ServersList" data-val-required="The Server field is required." data-val="true">                <option value="--">Select a Server</option>            <option value="1">Arkenstone</option><option value="2">Anduin (DE)</option><option value="3">Belegaer (DE-RP)</option><option value="4">Brandywine</option><option value="5">Bullroarer (Public Test Server)</option><option value="6">Crickhollow</option><option value="7">Dwarrowdelf</option><option value="8">Eldar</option><option value="9">Elendilmir (Oceanic)</option><option value="10">Estel (FR-RP)</option><option value="11">Evernight (UK)</option><option value="12">Firefoot</option><option value="13">Fornost (RU-RP)</option><option value="14">Gilrain (UK)</option><option value="15">Gladden</option><option value="16">Gwaihir (DE)</option><option value="17">Imladris</option><option value="18">Landroval (US-RP)</option><option value="19">Laurelin (UK-RP)</option><option value="20">Maiar (DE)</option><option value="21">Meneldor</option><option value="22">Mirkwood (RU)</option><option value="23">Nimrodel</option><option value="24">Morthond (DE)</option><option value="25">Palantir (Private Test Server)</option><option value="26">Riddermark</option><option value="27">Silverlode</option><option value="28">Sirannon (FR)</option><option value="29">Snowbourn (UK)</option><option value="30">Vanyar (DE)</option><option value="31">Vilya</option><option value="32">Windfola</option><option value="33">Withywindle (UK)</option></select>        </div>

If I look at the output from Visual Studio while debugging this section I see this:

Disabled: false

Group: null

Selected: true

Text: Brandywine

Value: 4

All others in that listing return false on the selected.  This is essentially the same for all the other lists.  What I get on the View is the "Select a Server" showing.  So how do I get this to display the selected value when displaying the page.  And with the validation, it returns the Select a Server as valid, I would guess because this never shows that these dropdown lists are invalid.  I could leave everything blank on the screen for the Create and I only get two validation errors, while I should be getting 6 errors.

Does anyone see what I am doing wrong?

Captcha appear and disappear

$
0
0

Hello, 

I have a captcha problem.

it was working before net core (framework) template 1.1 and now it just appear for a second and disappear ( chrome and opera )

any idea ?

Controller

.........

Bitmap s_image = new Bitmap(160, 30);
Graphics s_graphic = Graphics.FromImage(s_image);

Font s_font = new Font("Arial", 16, FontStyle.Bold);
SolidBrush s_brush1 = new SolidBrush(Color.White);
HatchBrush s_brush2 = new HatchBrush(0, Color.White, Color.FromArgb(255, 51, 51));

s_graphic.FillRectangle(s_brush2, 0, 0, s_image.Width, s_image.Height);
s_graphic.DrawString(s_secword, s_font, s_brush1, new PointF(15, 2));

Response.ContentType = "image/gif";

s_image.Save(HttpContext.Response.Body, ImageFormat.Gif);

return View();

cshtml

.......

<img src="@Url.Action("captchax", "captcha", new { area = "project" }, null)" style="display: inline-block; " />

........

Why the concurrent performance of my server(ASP .net core + MySQL) is very low? something wrong in my .net code?

$
0
0

I used asp.net core and MySQL.  the connector I used is connector/net. I use apache bench to test, reques per second is only 4.06

Is this normal? I use java spring to test, the request per second is 1000+ ....

I just want to know is it because something wrong in my code?

Doubts about the access from the WAN on site asp.net core ...

$
0
0

Hello to all, Icreated a websitewithasp.net1.1coreMVCI havemade all the necessaryconfigurations, i can connecttothe home pageonly ifI map"127.0.0.1"or "public IP"withvirtual sitename in the hosts fileof the machinefrom whichI connect(serverin the first caseandfrom anyremote machinein the second case)with the address"http: //virtualsitename: port"Otherwiseif I connectwith the followingURL"http://IP:9191/ virtualsitename"or "http://IP:9191" I havethe following error:

Bad Request - Invalid Hostname

HTTP Error 400. The request hostname is invalid.

Ifto get to mysiteIuse a link locatedon another siteas it should be thelink?


Asp.net Core Data Annotations failing to decorated multiples of the same model type.

$
0
0

I'm using a partial view to create a security question and answer view using a model. Besides the issue of naming each one with a index number. That is a whole seperate issue all together.
I want 3 security questions and answers. I add the partial view 3 times to create 3 security questions and answers. Of those 3 only the the first security question and answer is decorated with
model requirements. The next 2 is missing the model requirements. I decided this is a [BUG]. At some point the web controls get decorated with the model requirements. For some reason it only does one
and ignores the reset.

What is going on here and why is this not working failing

Model:

public class QNAViewModel
{
     [Required(ErrorMessage = "The question field is required")]
     public String Question { get; set;}

     [Required(ErrorMessage = "The answer field is required")]
     [StringLength(250, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
     public String Answer { get; set; }

}

Partial View:

@model MyNameSpace.Models.ProfileViewModels.QNAViewModel
@{
    string qId = String.Format("Question{0}", ViewData["Index"]);
    string aId = String.Format("Answer{0}", ViewData["Index"]);
}<div class="form-group"><label asp-for="Question" for="@qId" class="col-md-2 control-label"></label><div class="col-md-5"><select asp-for="Question" id="@qId" name="@qId" class="form-control" asp-type="securityquestion"></select><span asp-validation-for="Question" data-valmsg-for="@qId" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Answer" for="@aId" class="col-md-2 control-label"></label><div class="col-md-5"><input asp-for="Answer" id="@aId" name="@aId" class="form-control" /><span asp-validation-for="Answer" data-valmsg-for="@aId" class="text-danger"></span></div></div>

Dynamic Model Binding with Repeating Inputs

$
0
0

Is there a "proper" way to setup model binding for dynamically adding, editing, and deleting elements in .NET Core? I came across this article (https://www.codeproject.com/Tips/766214/List-Model-Binding-in-MVC) which goes over the concept I'm trying to build. I'm new to ASP.NET MVC and I wanted to see if anyone had suggestions or examples on a good way to handle something like this.

Thanks in advance for any help.

Project Hierarchy, What Technologies to use?

$
0
0

Hi,

I want to write application separated to 3 parts. Client Service, Service, Web.

Let's say we have for example 5 computers and 1 server. Each computer will run Client Service. Server will run Service and Web.
I thinking of Client Service as Windows Service Project. Service as WCF Service and Web as ASP.NET Core (.NET Framework).

Client Service will collect data about users and send it to WCF Service to write it to db.
Web will work as data viewer with graphs etc.

So what's the question?
Currently thinking of if its possible for WCF to connect to ASP.NET Core or is there a better solution instead of WCF? I think WebAPI is not great solution for this.
Also do you think its better to design for each database table own manager for add/edit/delete etc. or share through WCF DatabaseContext to Web for display or make own DatabaseContext for Web? Or Just share from WCF ConnectionString?

I don't have much experience in designing in this concept. So better to ask someone who's experienced :)

Thanks.

Environment Variable in Class Library

$
0
0

Hi!

I'm trying to create a class library in my solution, and I want it to access the Environment Variable, so I can choose the correct db connection string.  Does anybody know how to do that?  Since my main project is dependent on the class library, I can't make the class library dependent on the main project to access that variable.

Thanks!

Redirect page is not working in Unauthorized Access ( 401 )

$
0
0

Hi,

How we can ridirect the current page When user access the Unauthorized content. 

Index Page

When I click on the "Click" button in Index Page, Then It will redirect to Home controller.

<div class="row"><div class="col-md-12"><h1>Welcome to ASP.NET Core Identity !!</h1><p>Security !!</p><a asp-controller="Home" asp-action="Home" class="btn btn-success">Click</a></div></div>

Home Controller

We already set Authorize in Home Action in Home Controller. So the click event will fire Home Action method. But it showing blank page !! 401 

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RegistrationForm.Models;

namespace RegistrationForm.Controllers.WebApp
{
    public class HomeController : Controller
    {
        private IRegRepository _repository;

        public HomeController(IRegRepository repository)
        {
            _repository = repository;
        }

        [Authorize]
        public IActionResult Home()
        {
            var data = _repository.GetAllRegistrations();
            return View(data);
        }

        public IActionResult Index()
        {
            return View();
        }
    }
}

Startup.cs

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RegistrationForm.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

namespace RegistrationForm
{
    public class Startup
    {
        private IConfigurationRoot _config;
        private IHostingEnvironment _env;

        public Startup(IHostingEnvironment env)
        {
            _env = env;
            var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");
            _config = ConfigBuilder.Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddIdentity<RegistrationUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail = true;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/Auth/login";

            }).AddEntityFrameworkStores<RegContext>();

            services.AddMvc(config =>
            {
                if (_env.IsProduction())
                {
                    config.Filters.Add(new RequireHttpsAttribute());
                }
            });


            services.AddSingleton(_config);
            services.AddEntityFrameworkSqlServer().AddDbContext<RegContext>();
            services.AddScoped<IRegRepository, RegRepository>();
            services.AddTransient<RegContextSeedData>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
            ILoggerFactory loggerFactory, RegContextSeedData seeder)
        {
            loggerFactory.AddConsole();

            app.UseIdentity();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();

            app.UseMvc(config =>
           {
               config.MapRoute(
                   name: "Default",
                   template: "{controller}/{action}/{id?}",
                   defaults: new { controller = "Home", action = "Index" }
                   );
           });
            try
            {
                seeder.SeedData().Wait();
            }
            catch (Exception ex)
            {

                throw ex;
            }


        }
    }
}

ASP.NET Core application not freeing memory

$
0
0

I have an ASP.NET Core application running behind IIS in production that is not freeing memory on its own until the application pool recycles itself.  Every request causes the memory to increase.  

I am able to reproduce this with a fresh ASP.NET core application using Visual Studio 2017 with the ASP.NET Core Web API template.  I created the following method and called it from postman about 100 times:

namespace WebApplication3.Controllers
{
    [Route("")]
    public class ValuesController : Controller
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            var message = "test";
            return Enumerable.Repeat(message, 100000);
        }
    }
}

I did a publish build and launched the application from the command line.

The memory usage goes up and is never released:

dotnet memory

Here is my dotnet version

PS C:\Windows\system32> dotnet --version
1.0.0

I expect the memory to go down after the requests are done being served.  Does anybody have any idea what is going on?

VS2017 Scaffolding error Microsoft.VisualStudio.Web.CodeGeneration.Utils

$
0
0

I am trying to just do an controller scaffolding on a ASP.NET Core application I and I get the following error

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.Web.CodeGeneration.Utils, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
at Microsoft.VisualStudio.Web.CodeGeneration.Design.Program.Main(String[] args)

I looked on Google but they are not many references about VS2017 yet.

Thanks


Need Help On C# Multi Threading(Dynamic Threads)

$
0
0

hello ,
i have a asp.net application which pulls data from oracle database and load data into ms sql database . currently we are using year based static Threads. but the problem is when every year changes we need to create new thread and deploy the application . can anyone help me to create Threads dynamically every year . bellow is my current code 

 public class Program
    {
       public static void Main(string[] args)
        {
            DataLoading dl1 = new DataLoading("2004");
            Thread t1 = new Thread(dl1.LoadDatabyyear);

            DataLoading dl2 = new DataLoading("2005");
            Thread t2 = new Thread(dl2.LoadDatabyyear);

            DataLoading dl3 = new DataLoading("2006");
            Thread t3 = new Thread(dl3.LoadDatabyyear);

            DataLoading dl4 = new DataLoading("2007");
            Thread t4 = new Thread(dl4.LoadDatabyyear);

            DataLoading dl5 = new DataLoading("2008");
            Thread t5 = new Thread(dl5.LoadDatabyyear);

            DataLoading dl6 = new DataLoading("2009");
            Thread t6 = new Thread(dl6.LoadDatabyyear);

            DataLoading dl7 = new DataLoading("2010");
            Thread t7 = new Thread(dl7.LoadDatabyyear);

            DataLoading dl8 = new DataLoading("2011");
            Thread t8 = new Thread(dl8.LoadDatabyyear);

            DataLoading dl9 = new DataLoading("2012");
            Thread t9 = new Thread(dl9.LoadDatabyyear);

            DataLoading dl10 = new DataLoading("2013");
            Thread t10 = new Thread(dl10.LoadDatabyyear);

            DataLoading dl11 = new DataLoading("2014");
            Thread t11 = new Thread(dl11.LoadDatabyyear);

            DataLoading dl12 = new DataLoading("2015");
            Thread t12 = new Thread(dl12.LoadDatabyyear);

            DataLoading dl13 = new DataLoading("2016");
            Thread t13 = new Thread(dl13.LoadDatabyyear);

            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            t5.Start();
            t6.Start();
            t7.Start();
            t8.Start();
            t9.Start();
            t10.Start();
            t11.Start();
            t12.Start();
            t13.Start();

            Thread joinThread = new Thread(joinAllThread);

            joinThread.Start(new Thread[] { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13 });
        }
       
        private static void joinAllThread(object obj)
        {
            Thread[] threads = obj as Thread[];
            foreach (Thread t in threads)
                t.Join();
        }
    }

   public class DataLoading
    {
        private string loadbyyear;
       
        public DataLoading(string loadyear)
        {
            this.loadbyyear = loadyear;
                                 
        }
        public void LoadDatabyyear()
        {
            
          // LoadDatabyyear(loadbyyear); //some method 
           
        }
    }

How to display title from user control ascx file

$
0
0

Hi,

I have a Aspx page in that user control is loaded based on the user selection. Here i want to display the page title from Usercontrol ascx file (not from code behind). how can i achieve this. Please help.

Microsoft.AspNet.Razor 3.2.3 is not compatible with netcoreapp1.1

$
0
0

Hello

When I use VS Community 2017 and try and install some new dependencies via NuGet Package manager (specifically, Razor tools, Static file and MVC) I get the following error:

 Package Microsoft.AspNet.Razor 3.2.3 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Microsoft.AspNet.Razor 3.2.3 supports: net45 (.NETFramework,Version=v4.5)
One or more packages are incompatible with .NETCoreApp,Version=v1.1.

I've clicked on the cog next to the package source and clicked the update button (so I have the most resent package list).

I'm trying to load these files as I am following an online course, and the next step is to load Microsoft.AspNetCore.Razor.Tools , Microsoft.AspNetCore.StaticFiles and Microsoft.AspNetCore.Mvc ( the video instructor is using a lesser version that 2017.. so is that the problem ?).

The tutor goes on to talk about editing the project.json file ( which is now superseded by the csproj file ) to load them...

can anyone help shed some light for me ?

thanks in advance

"DRY" form tag uniformity in one component or partial view

$
0
0

I have a number of form tags that look similar:

<form asp-area=@ViewBag.Area asp-controller=@ViewBag.Controller asp-action=@ViewBag.Action asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal">

It would be nice if I put everything in "<form ... >" into a "super ViewBag" or partial view so I have it all in one place in case of changes. I've unsuccessfully tried a number of ways. Any ideas?

System.IdentityModel.Metadata and X509SecurityToken not available in ASP.NET Core

$
0
0

I'm currently trying to get signing keys from Azure Active Directory based on the signing key rollover guide over at Microsoft docs in order to authenticate HTTP requests on an ASP.NET Core Web API endpoint I'm developing.

Although I migrated the source code shown in the article it doesn't seem like some references and classes are available in ASP.NET Core web apps such as System.IdentityModel.Metadata and classes like X509SecurityToken, MetadataSerializer, EntityDescriptor and X509RawDataKeyIdentifierClause.

Source code with types not found

I already searched on NuGet, but it doesn't seem like packages are available for System.IdentityModel and I'm not able to reference system assemblies in ASP.NET Core neither.

Which libraries shall I use in ASP.NET Core instead?

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>