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

Asp Core 1.1 share cookie Auth between application

$
0
0

Hi,

I try to share 2 authentication cookies between 2 applications.

In App1 : Startup.cs

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies",
                LoginPath = new PathString("/Account/Login"),
                AccessDeniedPath = new PathString("/Home/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName = "ASPTest",
                ExpireTimeSpan = new TimeSpan(1, 0, 0) //1 hour
            });

And in App2 : Startup.cs

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies",
                LoginPath = new PathString("/Account/Login"),
                AccessDeniedPath = new PathString("/Home/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName = "ASPTest",
            });

In Ap1 : AccountController.cs

       [HttpGet]
        public IActionResult Login(string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(string username, string password, string returnUrl)
        {
            if (username == password)
            {
                var claims = new List<Claim>
        {
            new Claim("Read", "true"),
            new Claim(ClaimTypes.Name, "ayayalar"),
            new Claim(ClaimTypes.Sid, "12345")
        };

                var claimsIdentity = new ClaimsIdentity(claims, "password");
                var claimsPrinciple = new ClaimsPrincipal(claimsIdentity);

                await HttpContext.Authentication.SignInAsync("Cookies", claimsPrinciple,
                    new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties { IsPersistent = true});

                if (Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }

                return Redirect("~/");
            }

            return View();
        }

In both Ap1 and Ap2 : I check after logged in (tested without database and login == password)

        public IActionResult Index()
        {
            var t = HttpContext.User;

            return View();
        }

In Ap1 which allows to login and create cookie, the cookie is created and when going on Home/Index the t variable is feed from Cookie==> it works!
In Ap2  when going on Home/Index the t variable is not feed from Cookie ==> it fails !

In Mozilla I'm able to see the cookie created within both App1 and App2, but App2 seems not able to load it.

I tried to follow the link : https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/compatibility/cookie-sharing but with no success as 

DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"))

does not build.

Did I miss some obvious point when trying to get access the cookie created from Ap1 with Ap2 ? My goal is to create a cookie from Ap1, and get all Claims from Ap2.

Thank you for your help

Nicolas


Running .NET core app in Linux

$
0
0

I am running my published .NET core app on Linux using "dotnet abc.dll &" command so it runs in the background. Will this be running forever? I heard from a friend of mine that Garbage Collector will kill the running application and we need something like"Supervisor" to keep the application running. Is this correct?

Thanks

Angelo

VS 2017 RTM - Asp.Net Core web app - F5 -> localhost is currently unable to handle this request.

$
0
0

Hi,
I created a new Asp.Net Core Web App.
The app is running fine from dotnet run command or the .exe
I would debug it directly from Visual Studio with F5 in IISExpress or the .exe 

When I press F5,  a small Chrome page opens but remains empty.

When I press Ctrl+F5, I get "localhost is currently unable to handle this request."

Any help would be great
txs

-Vince

.NET Core 2.0 support System.Configuration's "ConfigurationSection" ?

$
0
0

We're porting a .NET Framework 4.5 .dll to .NET Core (1.1 right now). At present we've got a custom configuration in the app.config via a customConfigurationSection containing custom ConfigurationElement from theSystem.Configuration namespace.

We also noticed that the .NET Core 2.0 Roadmap says

.NET Core gain over 5,000 APIs from .NET Framework as part of this work making it a broader platform.

So will .NET Core 2.0 add back support for the traditional ConfigurationElement and ConfigurationSection? That way we could skip .NET Core 1.1 and it's intermediate porting efforts.

Unable to Delete A Record

$
0
0

Hi,

The HttpPost seems to be in problem in an ASP Core CRUD.

SrcSys & CustId represent the elements of composite key:

        public async Task<IActionResult> Delete(string _SrcSys, string _CustId)
        {
            if (_SrcSys == null || _CustId == null)
            {
                return NotFound();
            }
            var customer = await _context.Customers
                .AsNoTracking()
                            .SingleOrDefaultAsync(Cust => Cust.SrcSys == _SrcSys && Cust.CustId == _CustId);
            if (customer == null)
            {
                return NotFound();
            }
            return View(customer);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeletePost([Bind("SrcSys,CustId,CustNm")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                _context.Remove(customer);
                await _context.SaveChangesAsync();
                ViewData["ErrorMessage"] = customer.CustId;
                return RedirectToAction("Index");
            }
            return View(customer);
        }

I am led to the Internal Server Error page declaring:

"Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions"

While it's the local PC there can't be a chance of concurrency I think.

Please see if you can help.

problem with additional layout page

$
0
0

I would like to make a layout page based on the view shown below, with the content in the div with class "form-group" inserted in the resulting content pages. Or better yet, I'd like to make all the values after the "asp-for" and "asp-validation-for" tag helpers variable in each content page. Each content page would also have to contain a different model at the top. All this would help tremendously in my quest to make this a "DRY" project. Any hints?

PROPOSED LAYOUT PAGE:

@RenderBody()
@{await Html.RenderPartialAsync("_BeginAllPartial").ConfigureAwait(false); }<form asp-area=@ViewBag.Area asp-controller=@ViewBag.Controller asp-action=@ViewBag.Action asp-route-returnurl=@ViewData["ReturnUrl"] method="post" class="form-horizontal"><input type="hidden" asp-for="ID" />

    @{await Html.RenderPartialAsync("_FormBeginPartial").ConfigureAwait(false); }<div class="form-group"><div class="form-inline"><label asp-for=@RenderSection("ctrl01Label", required: true) class="control-label col-md-3"></label><input asp-for=@RenderSection("ctrl01Input", required: true) class="form-control col-md-offset-1 col-md-4" autofocus tabindex="10" /></div></div>


    @{await Html.RenderPartialAsync("_FormEndPartial").ConfigureAwait(false); }</form>

@{await Html.RenderPartialAsync("_EndAllPartial").ConfigureAwait(false); }


PROPOSED CONTENT PAGE:

@model InstructionalMaterialViewModel
@Layout="_CreateEditLayout"

@section ctrl01Label{"Isbn"}
@section ctrl01Input{"Isbn"}

Following is the error I get; I also find it strange that the term "section" didn't Intellisense for me.

An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately.

/Features/Shared/Lookup/_CreateEditLayout.cshtml

An expression tree may not contain a named argument specification
<label asp-for=@RenderSection("ctrl01Label", required: true) class="control-label col-md-3"></label>
An expression tree may not contain a named argument specification
<input asp-for=@RenderSection("ctrl01Input", required: true) class="form-control col-md-offset-1 col-md-4" autofocus tabindex="10" />

Generated Code

An expression tree may not contain a dynamic operation
#pragma warning restore 199

How can I get offline package named " microsoft.entityframeworkcore.sqlserver" ?

$
0
0

Sir

Please guide about

How can I get offline package named " microsoft.entityframeworkcore.sqlserver" ?

Regards

When I issue the command "dotnet ef database update" I get the message "no excecutable found matching command "dotnet ef"

$
0
0

sir,

When I issue the command

"dotnet ef database update"

I get the message

"no excecutable found matching command "dotnet ef"

Please guide

Regards


HTTP Error 502.5 - Process Failure whem application is run from Visual Studio

$
0
0

I've seen this post, but it is not my case cause I run my project from Visual Studio. It is not a deployed application.

I've recently installed Visual Studio 2015 Professional and I am running locally ASP.NET Core Webapplication. What I see is error when I run application is:

HTTP Error 502.5 - Process Failure

Common causes of this issue:

The application process failed to start The application process

started but then stopped The application process started but failed to

listen on the configured port

I've already installed the follwing packages at my PC:

  1. DotNetCore.1.0.1-VS2015Tools.Preview2.0.3
  2. DotNetCore.1.0.4_1.1.1-WindowsHosting
  3. dotnet-dev-win-x64.1.0.1
  4. dotnet-win-x64.1.1.1

Does anybody know how can I resolve this error?

Change date format.

$
0
0

Hey, I am trying to change the format validation for a date to "day/month/year" but whatever I do, it keeps validating for "month/day/year"

This is my Model

        [RequiredAttribute, DisplayAttribute(Name = "Date")]
        [DisplayFormat(DataFormatString = "{0: dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime Date { get; set; }

And this the HTML

<div><label asp-for="Date"></label><input asp-for="Date" /><span asp-validation-for="Date"></span></div>

Anyone knows how to fix it?

Determine the URL and PORT that servers is listening on

$
0
0

In an ASP.NET Core web service application, is there a way to determine the base URL and PORT being used once the server starts up?

I want to log this to as part of our standard service startup sequence for admin and support staff.

Most of the time it will be port 80, but not always and when debugging with IIS Express a (random-ish) port number is used.

I did discover ServerAddressesFeature and when I get at that the URL sort of looks OK but the port is different to the actual port being used.

i.e. IIS Express says its using port 27988 but the port seen in the server addresses feature class is 27750 !

Any help is much appreciated.

NOTE: This information is required at app startup, it is not being determined during the execution of a controller/request.

How to change the date format in razor

$
0
0
Razor
<input asp-for="Movie.ReleaseDate" class="form-control" />

In the view, the releaseDate is the default format 0001-01-01T00:00:00.000

Steps to build and run an ASP.NET CORE WEB APPLICATION.

$
0
0

Sir

Please give some guidance on how to build and run an ASP.NET CORE WEB APPLICATION.

Regards

Recommend Platforms for Trying out ASP.NET Core and Entity Framework Core on Linux

$
0
0

I have a windows 10 notebook computer and I would like to try out running the VS Code editor to develop a small ASP.NET/MVC Web site that uses Entity Framework with PostgresSQL on Linux.

What do you recommend? I could

(1) Create an Ubuntu VM and use the Hyper-V GUI to run a session on the VM.

(2) What about Docker? I'm new to docker I just installed Docker on my Windows 10 and I can get a bash prompt. It works! Yahoo!  Is it good for anything serious? Can I develop an ASP.NET core web site using docker? Would I want to? I'm not sure how to share files with this bash prompt. Can I install .NET core and postgressql and g++ on it?

(3) What about inexpensive third party hosting. Wow! I saw an ad for $1/month on this site. That is pretty cheap! Last fall I ran the HelloWorld program in C# on Core on Nitrous.IO for free and it looks like they went out of business! Shucks.... (I guess they did not charge enough) Perhaps I could use Cygwin X on windows and Xhost to run VSCode on a third party Linux VM somewhere? Any recommendations?

Without buying new hardware, those are the only options I can think of. (I forgot about creating a Linux partition and creating a dual Linux/windows boot system -- but that is too old fashioned for me) Are there any other options?

Let me know what you have tried and what you recommend for running VS Code and postgressql and a little demo ASP.NET Core Web site.

Thanks

Siegfried

Accessing current user data outside the controller


Web API authorization without JWT tokens

$
0
0

Can I just use standard identity system that ships with ASP.NET Core when writing a Web API? I mean without JWT tokens, just throw in AddIdentity to ConfigureServices and use [Authorize] above my API controller. Just like standard MVC application without any API. I have single page application and I want my login and register pages to be multi-page. It's just easier than generating all those certificates, token configuration and searching for some token generation library or hosting a separate server like IdentityServer. What are disadvantages of using it over recommended JWT?

HttpPost Delete MVC for Composite Keys

$
0
0

I have a table with three columns with first two formulating the composite key

  1. SrcSys (CompositeKey Part I)
  2. CustId (CompositeKey Part II)
  3. CustNm

I am new to ASP & starting with MVC Core.

The following code for the delete's get method works well:

public async Task<IActionResult> Delete(string _SrcSys, string _CustId)
    {
        if (_SrcSys == null || _CustId == null)
        {
            return NotFound();
        }
        var customer = await _context.Customers.SingleOrDefaultAsync(Cust => Cust.SrcSys == _SrcSys && Cust.CustId == _CustId);
        if (customer == null)
        {
            return NotFound();
        }
        return View(customer);
    }

The relevant code of Delete.cshtml is:

@modelRiskDotNet.Models.Customer@{ViewData["Title"]="Delete";}<hr /><dl class="dl-horizontal"><dt>SrcSys</dt><dd>@Html.DisplayFor(model => model.SrcSys)</dd><dt>Cust ID</dt><dd>@Html.DisplayFor(model => model.CustId)</dd><dt>Customer</dt><dd>@Html.DisplayFor(model => model.CustNm)</dd></dl><form asp-action="Delete"><div class="form-actions no-color"><input type="submit" value="Delete"class="btn btn-default"/><p /><p /><input type="submit" value="Cancel"class="btn btn-default" a asp-action="Index"></div></form>

I need all the three fields to be appearing on the page, i.e. the Keys too and thats why I have added the same in the cshtml above.

In respect of the same what would be a change (if any) in Delete.cshtml and correct piece of code forHttpPost that you would recommend?

Thanks in advance.

Read appsettings.json from Class Library

$
0
0

I have a .NET CORE Class Library which is referenced by ASP.NET CORE Web Applications.

I know how to read and assign the values to a class in a CORE Web Application, but I want to be able to read a section in the appsettings.json file that belongs to the project that references the Class Library.

Any ideas??

Adding a controller for ApplicationUser.cs?

$
0
0

I'm trying to add a controller for the ApplicationUser.cs so that when a admin is logged in, they have the ability to view, edit, delete any records from the dbo.AspNetUsers table however I think I'm doing it wrong. Any ideas?

Here's the code for the ApplicationUser.cs:

namespace ProjectTest.Models
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        public string Summary { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        override public string UserName { get; set; }
        public string RoleType { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        override public string PhoneNumber { get; set; }
        override public string Email { get; set; }
    }
}

When I try to add a controller for the ApplicationUser model class, the controller gets created (including the view files) but fails to launch. The controller is the default code after creating a new controller.

Localization on _Layout.cshtml

$
0
0

I have a project where localization is working fine, except in _Layout.cshtml
What should I name the resource file when using _Layout.cshtml? (Views.Shared._Layout.en.resx don't work)

_Layout.cshtml:

@using Microsoft.AspNetCore.Http.Extensions
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization

@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
@inject IViewLocalizer LayoutLocalizer


<!DOCTYPE html><html><head></head><body><div style="margin:38px;margin-top:56px;" class="hidden-sm-down"><h2>@LayoutLocalizer["WelcomeHeader"] <b class="text_border_darkblue">MyTitle</b></h2><div style="text-align:center;margin-top:42px;">
                @LayoutLocalizer["WelcomeSub"]</div></div></body></html>

 

Viewing all 9386 articles
Browse latest View live


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