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

MVC Single page application authentication and authorization

$
0
0

I'm completely new to SPAs world and I'd like to build one using ASP.NET Core MVC as a back-end. But I don't know how to handle authentication in this case and the single user authentication option in visual studio is grayed out when choosing Web API.

Most of the web apps on the internet use separate pages for login and register(or one page for login/register, for example, asana.com) for security reasons and page loading speed. How should my project look like to achieve a similar effect to asana.com? I'm really confused. Should I have a separate Web API project for the API and separate project for the website using the API or a single project with identity system and just use [Authorize] on controllers returning JSON for my js framework? There aren't many tutorials or courses on the web regarding this topic nor project samples on Github. 


VB.NET and .NET Core

$
0
0

When will I be able to use VB and .NET Core ?

View Components and Ajax Server Side Validations

$
0
0

My app requires the ability to send emails on multiple views. I'm trying to use a View Component so I can reuse my logic multiple places. When the user clicks the Send button I don't want to refresh the entire view...I want to validate the form and display any model errors, else send the email.

The setup below works fine for Client Side validation, but I'm not sure how to bring back the model errors server side and display them in the view. Any help is appreciated.

Default.cshtml (View Component - using jquery-ajax-unobtrusive)

@model EmailViewModel<div id="Email"><div class="row section-buffer"><div class="col-sm-12"><span class="section-header">Email</span></div></div><hr /><form id="EmailForm"
          method="post"
          class="form-horizontal"
          asp-controller="Email"
          asp-action="Send"
          data-ajax="true"
          data-ajax-method="POST"
          data-ajax-success="sendEmailSuccess"
          data-ajax-failure="sendEmailFailure(xhr, status, error)"
          data-ajax-update="Email"><div class="form-group form-group-sm"><label class="description-label col-sm-3" asp-for="From"></label><div class="col-sm-9"><input class="form-control" asp-for="From" /><span asp-validation-for="From" class="text-danger"></span></div></div><!-- remaining fields omitted --><div class="form-group form-group-sm"><div class="col-sm-9 col-sm-offset-3"><button type="submit" class="btn btn-primary">Send</button></div></div></form></div>

EmailViewModel

public class EmailViewModel
{
    [Required]
    public string From{ get; set; }
    //remaining properties omitted
}

EmailController

[HttpPost]
[Route("/email/send")]
public ActionResult Send(EmailViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        //how do return my model errors back to my View Component?
    }
    else
    {
        //do send logic here
        return Content("Success");
    }
}

What is default timeout value for CookieAuthenticationOptions in asp.net core MVC

$
0
0


Hi,
I am using cookies middleware authentication in ASP.Net core project.I want to know default timeout value for 'CookieAuthenticationOptions.ExpireTimeSpan'.
Also It would be great if anyone can specify default flag value for 'CookieAuthenticationOptions.SlidingExpiration'.
I am not able to get official default values for CookieAuthenticationOptions anywhere. So any help in this regard would be great.

Thanks,
Shashikant

windows authentication and token authentication

$
0
0

Is it possible to combine both windows and token authentication method in asp.net core? I have been looking for some tutorial for this but can't find any. Or it is totally impossible to combine both authentication method?

Trying to start a SignalR connection from an ASP.NET Core action call gives TypeLoadException

$
0
0

The setup I'm trying to accomplish is this: I have a signalR server that supports 2 types of clients - one type that supplies data and another that receives data. When a "receiver" type client chooses one of the "sender" type clients to monitor, the SignalR server makes a call to the "sender" client to open a connection. The "sender" client is an ASP.NET Core instance running as a Windows Service. The POST request calls a service that starts a timer and tries to open a SignalR connection as a client. The POST request is going through as expected and it calls the service properly. When the service tries to open the SignalR connection, though, I get: System.TypeLoadException in SignalR.Client.dll (Inheritance security rules violated by type: 'System.Net.Http.WebRequestHandler'. Derived types must either match the security accessibility of the base type or be less accessible).

The action method in the controller looks like this:

[HttpPost]
public IActionResult StartUpdate()
{
    _updateDriver.StartTiming();

    return Ok("Timing has started");
}

And the method in the service looks like this:

public void StartTiming()
{
    if (!_isTiming)
    {
        try
        {
            _hubProxy = _hubConnection.CreateHubProxy("RemoteDataServerHub");
            _hubConnection.Start().Wait();
            _hubProxy.Invoke("JoinGroup", "Sender").Wait();
            _timer.Start();
            _isTiming = true;
        }
        catch (Exception ex)
        {
            Debug.Print(ex.Message);
            _isTiming = false;
        }
    }
}


The exception is thrown on the _hubConnection.Start().Wait() line. Does anyone have any idea what's going on here? I'm not very experienced in web applications or ASP.NET Core or SignalR. I may be biting off a bit more than I can chew here. But if anyone can point me in the right direction, it would be much appreciated!

Thanks!

How to change the default language of new core mvc project

$
0
0

Used to create mvc5 project, the UI default language was Chinese, when I switched to core mvc ,found the default language is english, anyone know how to change the setting

How to load multiple instances of a Dll in ASP.NET Core?

$
0
0

Hello. We have a piece of software that is used internally that has been turned into a Dll. It's written in C++. The desire was to run this on multiple platforms (Mac/Linux/Windows) as a service on the local network. There are 3 versions of this Dll: one for Mac, one for Linux and one for Windows. I've written a basic ASP.NET Core Web API that exposes the underlying functionality of the Dll via P/Invoke and a RESTful interface (my first), and I'm also in the process of writing a WPF client to pair with this new Web API service. The problem I have is that the Dll that was written is making heavy use of global data (arrays, variables, etc.) Therefore, if two or more clients are using the web API they will collide with the Dll's global state data. What I need is a way for each client to somehow load its own instance of the Dll.

After hunting around over the weekend I've discovered that this seems to be a pretty common problem and the standard "fix" is to dynamically make copies of the Dll file into a new file path and load it from there at runtime, for example:  http://stackoverflow.com/questions/15997037/loading-multiple-instance-of-dll-c-net  Is a anyone aware of a better way of getting multiple "instances" of a Dll into memory other than dynamically copying/loading from the file system, or is this still the only way to do this? If this is still the only way to do it will this hack also work for Mac and Linux environments?


ASP.NET Core on IIS: 502 - Web server received an invalid response while acting as a gateway or proxy server.

$
0
0

Hi guys,

I try to performence test my asp.net core 1.0.1 website. I use loader.io to get 4000 client's to run this site but i get this error on asp.net core. If i run the same code in asp.net 4.6 it runs very well. Can anybody tell my why i cant handle same load on my asp.net core site like my asp.net 4.6?

502 - Web server received an invalid response while acting as a gateway or proxy server.

There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.

Screenshots: https://thusan.tinytake.com/sf/MTA4Mzg1NV80MzMzNzMw

ASP.NET 4.6: https://thusan.tinytake.com/sf/MTA4Mzg1OF80MzMzNzMz

ASP.NET core: https://thusan.tinytake.com/sf/MTA4Mzg1OV80MzMzNzM0 

I'm running both sites from IIS on a Windows 2012 r2.

Remote start an ASP.NET Core Web API from a desktop client?

$
0
0

Hello. I've written an ASP.NET Core Web API as a service for a desktop client I'm writing. I intend to publish it as a self-contained .NET Core app and just copy the folder over to the host computer. When I launch my WPF client I would like the web api to start as well. Is there a way for the desktop client to launch the server, specifying the port the server should start listening on?

Share credential across multiple database

$
0
0

Hi,

we'are going to start two new ASP Core 1.1 web site projects using Identity.

is-it possible to share the same account information (ie role, etc ..) get from logging to the first application, when we'll access/redirected to the second application (which has itself  a different database). And vice versa.

Is there a simple way to handle this requirement ? 

Please help us as we're begginers.

Many thanks.

JSON formatter and Localization settings

$
0
0

Hi

In my project I`ve set my localization options as follows:

            var dtf = new DateTimeFormatInfo
            {
                ShortDatePattern = "dd.MM.yyyy",
                LongDatePattern = "dd.MM.yyyy HH:mm",
                ShortTimePattern = "HH:mm",
                LongTimePattern = "HH:mm"
            };
            var nf = new NumberFormatInfo
            {
                CurrencyDecimalSeparator = ",",
                CurrencyGroupSeparator = ".",
                NumberDecimalSeparator = ",",
                NumberGroupSeparator = ".",
                NumberDecimalDigits = 2
            };

            var supportedCultures = new[]
{
                      new CultureInfo("en-US") { DateTimeFormat = dtf, NumberFormat = nf },
                      new CultureInfo("en-GB") { DateTimeFormat = dtf, NumberFormat = nf },
                      new CultureInfo("en") { DateTimeFormat = dtf, NumberFormat = nf },
                      new CultureInfo("pl-PL") { DateTimeFormat = dtf, NumberFormat = nf },
                      new CultureInfo("pl") { DateTimeFormat = dtf, NumberFormat = nf }
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-US"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });

However when I try to get some data through my API controller (with Accept-Language set to pl-PL) I get the following JSON result (only one decimal digit and dot instead of coma as a decimal separator):

"netValue": 120,"grossValueAdded": 147.6,

How to force my app to present JSON data in the correct format like this?

"netValue": 120,00,"grossValueAdded": 147,60,

What versions of RHEL are supported?

$
0
0

Hello, I am seeing conflicting information online as to the versions of Red Hat Enterprise Linux that .NET Core can run on. I have an ASP.NET Core Web API targeting .NET Core 1.1 and intend to run on RHEL 6.8. Is this possible? Thank you in advance.

-L

Convert object to list dictionary

$
0
0

Hey everyone,

I'm creating a function to create my breadcrumbs out of a list that is placed in my datatoken from the route. I got the list out of the datatoken as a object but how do I convert it back to that list with dictionaries?

With this I made the list with dictionary

public class ParentUrlParents
{
    public List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
}

public static Dictionary<string, object> ChildUrlParents;

I tried things like this to convert it back

object ObjectBreadcrumbs = RouteData.DataTokens.FirstOrDefault(x => x.Key == "ParentUrlParents").Value;
//ParentBreadcrumbs ParentBreadcrumbs;

var s = ((Dictionary<string, object>)ObjectBreadcrumbs).ToList();

var t = (List<Dictionary<string, object>>)ObjectBreadcrumbs;

But then I got this error:

Unable to cast object of type 'ParentUrlParents' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]'.

ASP.NET Core MVC Rewrite and Default document

$
0
0

I'm trying to set Core MVC Rewrite so:

  • when
    localhost/part
    is requested, it responds with the default
    localhost/part/index.html
  • when
    localhost/part/[anything]
    , then still responds with
    index.html
    (
    localhost/part/index.html
    )

Here's what I have now:

app.UseRewriter(new RewriteOptions().AddRewrite("part(\\/.*)?", "part/index.html", true));

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(...);

So now, when

localhost/part/[anything]/[something]
is requested, it does serve
index.html
. But it serves it as
localhost/part/[anything]/[something]/index.html
and this is a problem with Angular's BASE_HREF. So app showsLoading... and nothing else is loaded obviously. Hm... This requires a fix from Angular's part. And I have no idea for the fix right now. Anyone?


JsonConvert.Deserialize throwing exception in Asp.Net Core

$
0
0

Hi.  I'm new to asp.net core and to asp.net in general.  I am trying to consume a rest service, here is a snippet of code:

return await Task.Run(() =>
{
    using (HttpClient client = new HttpClient())
    {
        IEnumerable<T> result = null;
        var data = client.GetAsync(GetUri()).Result;
        var jsonResponse = data.Content.ReadAsStringAsync().Result;
        if (jsonResponse != null)
        {
            result = JsonConvert.DeserializeObject<IEnumerable<T>>(jsonResponse);
        }
         return result;
    }
});

this issue is the JsonConvert.DeserializeObject, it throws an exception:  

Could not load file or assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.

System.Core isn't referenced in the project nor can I reference it.  Here is a copy of my .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"><OutputType>exe</OutputType></PropertyGroup><PropertyGroup><TargetFramework>netcoreapp1.1</TargetFramework></PropertyGroup><PropertyGroup><PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback></PropertyGroup><PropertyGroup><UserSecretsId>aspnet-GreenLakeCore-da0d49f4-e6a5-4d81-ad64-77a20dc9af43</UserSecretsId><ApplicationIcon /><OutputTypeEx>exe</OutputTypeEx><StartupObject /></PropertyGroup><ItemGroup><Compile Remove="Data\Migrations\**" /><Content Remove="Data\Migrations\**" /><EmbeddedResource Remove="Data\Migrations\**" /><None Remove="Data\Migrations\**" /></ItemGroup><ItemGroup><Content Include="wwwroot\images\042015-Lenny.jpg" /></ItemGroup><ItemGroup><PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" /><PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" /><PackageReference Include="Microsoft.AspNetCore.Mvc.TagHelpers" Version="1.1.2" /><PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" PrivateAssets="All" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" PrivateAssets="All" /><PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" PrivateAssets="All" type="Build" /><PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" /><PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" PrivateAssets="All" /><PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" /><PackageReference Include="Newtonsoft.Json" Version="10.0.2" /><PackageReference Include="RestSharp.NetCore" Version="105.2.3" /><PackageReference Include="System.ComponentModel.Annotations" Version="4.3.0" /></ItemGroup><ItemGroup><DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" /><DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" /><DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" /></ItemGroup><ItemGroup><None Include="wwwroot\Index.html" /></ItemGroup><ItemGroup><ProjectReference Include="..\Projection\Projection.csproj" /></ItemGroup><ItemGroup><Reference Include="System.Runtime.Serialization"><HintPath>..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.Runtime.Serialization.dll</HintPath></Reference></ItemGroup><ItemGroup><Folder Include="Migrations\" /><Folder Include="Migrations\" /><Folder Include="Migrations\" /></ItemGroup></Project>

There is also system.Runtime.Serialization listed under Assemblies in the Dependencies section.  
My question is this:

Is there a problem with NewtonSoft for AspNet core or do I have something wrong in my dependencies?

Thanks

ASP.NET Core SPA w/ API using AD FS 3.0

$
0
0

Hi

Is there a way to use AD FS 3.0 for Authentication in an ASP.NET Core SPA app (ng4) with API?
I'm building an Angular (4) application and would like to use VS 2017 and ASP.NET core as it (next version of angular mvc template) supports
ng4 using webpack but I have to authenticate users using AD FS 3.0 for now as an update to 4.0 is not possible yet.

My fallback is to use ASP.NET 4 (MVC/Web API) but found no samples on how to use ng4 tooling with MVC5.

Any help appreceated... :-)

Sebastian

asp.net core migration isn't creating database

$
0
0

Hi:

I'm learning asp.net core and have run into a problem with migrations.  from the cli I can enter:

dotnet ef migrations add InitialCreate

it appears to work.  Then I can enter

dotnet ef migrations add IdentityClasses 

and that appears to work, . . . . meaning I can see the the files created in the Migrations folder.  The problem is that I can't find the database in my sql server object Explorer window.  I can't see it in ssms either.

My connection string is "Server=(localdb)\\MSSQLLocalDB;Database=GLCoreDB;Trusted_Connection=True;MultipleActiveResultSets=true;"

When I look at my SQL Server Object Explorer their is a (localdb)\MSSQLLocalDB (SQL Server 13.0.42-2 - xxxxx\sssss)

What happened to the database?

asp.net and aspnet core session sharing

$
0
0

hi, 

please suggest a better resource for asp.net and aspnetsession sharing among each other . 

best practices when using two applications full dotnet and aspnet core.

session sharnig among them 

The ASPNETCoreModule which is required to host .NET Core projects in IIS does not appear to be installed

$
0
0

I've just installed  Visual Studio 2015 Professional and have just created new ASP.NET Core Web Application project. When I run the  ASP.NET Core Web application

 project I've met the following exception(I am just hitting Ctrl+F5 to run the project in Visual Studio 2015):

The ASPNETCoreModule which is required to host .NET Core projects in IIS does not appear to be installed. Try repairing Visual Studio to correct the problem.

If I run other types of projects such as ASP.NET MVC or ASP.NET Web API, then they run perfectly.

The following SDK is already installed:

enter image description here

What I've tried to do:

  1. I have varied version attribute to  1.0.0-preview2-final, 1.0.1, 1.0.3:

    "Microsoft.NETCore.App": { "version": "1.0.3", "type": "platform" },

  2. I have installed DotNetCore.1.0.4_1.1.1-WindowsHosting:

enter image description here

  1. I have repaired Visual Studio 2015 Professional twice.

Does anybody know what I should do to fix the problem? Any help would be greatly apreciated

Viewing all 9386 articles
Browse latest View live