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

Custom Http version/protocol name

$
0
0

Hey,

for a project I want to use a asp.net core webapi project. However I came across a limit of using a custom HTTP version/protocol name using kestrel.

The line of that protocol starts with POST /Sts/Connect STS/1.0 and I found no way to change how that processing in asp.net core works. Currently I'm always facing a "UnrecognizedHTTPversion" exception.

I'm open for any ideas. Otherwise I have to fallback to a simple socket server and handle all these things on my own.


Select tag helper in a list

$
0
0

Hi,

I have a form with a list of objects (DayList). in each list item I like to use a select tag helper to alter the selected shift

This is my model:

public string ScheduleName { get; set; }
public bool NameChanged { get; set; }
public string Message { get; set; }

public class ScheduleDay
        {
            public int DayNr { get; set; }
            public Shift Shift { get; set; }
            public bool Changed { get; set; }
        }

public List<ScheduleDay> DayList { get; set; }
public List<SelectListItem> ShiftList { get; set; }


public void OnGet(int ScheduleId)
        { 
          //Get all data from Database.
        }

In My cshtml file I want to do this:

<table id="scheduleTable"><tr><th width="100px">
                    Day</th><th width="100px">
                    Date</th><th widht="100px">
                    Schift</th></tr>
            @foreach (var item in Model.DayList)
            {<tr><th width="100px">
                        @Html.DisplayFor(modelItem => item.DayNr)</th><th width="100px">
                        Date</th><th width="100px"><select asp-for="item.Shift.ShiftId" asp-items="@Model.ShiftList"></select></th></tr>
            }</table>

But I get the error message "Model does not contain a definition for "item" ...

How should I do this ?

Setting custom Displayname (shortening name) for SupportedUICulture

$
0
0

Hi guys,

From the below code, the view displays full name of cultures by default.

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name"><form asp-controller="Home" asp-action="SetLanguage"
          asp-route-returnUrl="@returnUrl"
          method="post" class="form-horizontal">
        @Localizer[""] <select id="forlang" style="max-width: 42px" name="culture" onchange="this.form.submit();"
                                        asp-for="@requestCulture.RequestCulture.UICulture.Name"
                                        asp-items="cultureItems"></select></form></div>

How can I make it so that items of select dropdown would display the cultures like I want to see. In other words, I don't want to have such a long culture names (for ex. "English (United Kingdom)") in my view, but shot names like in most of websites (for ex. "en").

Thanks in advance!

How can Pass the value given in datetime column into the function FillHolidayPerYear var href before DN

$
0
0

In my code

<div class="controls col-sm-9">
<div class='input-group date' id='ToDatePicker'>
<input type='text' asp-for="ToDate" class="form-control" onchange="calculateNetHours()" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>

function FillHolidayPerYear() {
var href = '/Employee/HolidayPlanner? DN=' + $("#dropdownDepot option:selected").val() + '&DPT=' + $("#dropdownDepartment option:selected").val() + '&EMP=' + $("#dropdownEmployee option:selected").val();
$("#lnkFilter").attr('href', href);
$("#lnkFilter").click();
}

Please can you advise me with suggested code to bring the datetime value into the argument before DN in href = '/Employee/HolidayPlanner? DN

500 - Internal server error when deploying a Core web site

$
0
0

Hello,

I'm just starting with ASP.NET Core, and tried to deploy one today. I was faced with the above error when I tried to load it.

I started VS2017, created a new MVC Core site, and published. I didn't change a thing, just published the site as it came out of the box.

I then copied the contents of the bin\Release\netcoreapp2.2\publish folder to my hosting company via FTP, and tried to load the site in a browser.

The hosting company installed Core 2.2 on the server. Do they need to do anything else? I only have control panel access (via SolidCP) to the server, not remote access, so there's only so much I can do.

If I look in my control panel for the site, I see the following warning...

System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Runtime.InteropServices.COMException: Filename: \\?\D:\HostingSpaces\testuser\test.mydomain.co.uk\wwwroot\web.config 
Error: 

at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(String bstrSectionName, String bstrSectionPath) 
at Microsoft.Web.Administration.Configuration.GetSectionInternal(ConfigurationSection section, String sectionPath, String locationPath) 
at SolidCP.Providers.Web.Iis.DirectoryBrowse.DirectoryBrowseModuleService.GetDirectoryBrowseSettings(ServerManager srvman, String siteId) 
at SolidCP.Providers.Web.IIs70.FillAppVirtualDirectoryFromIISObject(ServerManager srvman, WebAppVirtualDirectory virtualDir) 
at SolidCP.Providers.Web.IIs70.GetSite(String siteId) 
at SolidCP.Providers.Web.IIs80.GetSite(String siteId) 
at SolidCP.Server.WebServer.GetSite(String siteId) 
--- End of inner exception stack trace --- 
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at SolidCP.Providers.Web.WebServer.GetSite(String siteId) 
at SolidCP.EnterpriseServer.WebServerController.GetWebSite(Int32 siteItemId) 
at SolidCP.EnterpriseServer.esWebServers.GetWebSite(Int32 siteItemId) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at SolidCP.EnterpriseServer.esWebServers.GetWebSite(Int32 siteItemId) 
at SolidCP.Portal.WebSitesEditSite.BindWebSite()

The web.config file it mentions looks like this...

<?xml version="1.0" encoding="utf-8"?><configuration><location path="." inheritInChildApplications="false"><system.webServer><handlers><add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /></handlers><aspNetCore processPath="dotnet" arguments=".\BasicCoreSite.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" /></system.webServer></location></configuration><!--ProjectGuid: 2fbe438c-a8b2-4b5b-8224-eb5dfcb62107-->

I tried changing the value of stdoutLogEnabled to "true" to see if that would give me a log file, but I couldn't see anything appear.

Anyone any idea what went wrong? The hosting company don't know much about Core, so can't help.

Thanks for any help you can give.

beginner level AJAX question

beginner level question for razor syntax

$
0
0

If I assert that the variable "@i" counts from 0 to n, then how to create a string variable that ends with that number?

I have tried lots of permutations of ('idHide'@i) .

//where @i is to represent the counter value as this is inside a loop.<button onclick="myFunction('idHide@i')">Edit</button>

one more beginner level question

$
0
0

I got the ajax response working as hoped, I returned a List<MyClass> and I can see when I push F12 I am getting actual data back in JSON form.

However, I don't know how to turn it back from Json into a class again.

I am trying this, just as test code, and it does not work.

WHere it falls apart is at the var bead = parseJSON(asObjects[i]); 

and I don't know what I should be doing at this point.

Could someone please point me to the next step on turning my class that had been sent as JsonResult, back into a class?

function loadDoc() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200 ) {
                    var json = this.response;
                    var asObjects = jQuery.parseJSON(json);                    
                    var result = "";
                    var i;
                    for (i = 0; i < 10;i++)
                    {
                        var bead = parseJSON(asObjects[i]);
                        result += bead[0];

                    document.getElementById("demo").innerHTML = result;
                }
            };
            xhttp.open("GET", "/_ajax/?handler=Filter",true);
            xhttp.send();
        }


making a Dictionary available to another project within the same solution - no success

$
0
0

Project TcpServer populates a List<IClient> clients

In project CommandHandler there is:

private List<IClient> clients;

public void Setup(List<IClient> clients)
        {
            this.clients = clients;
        }

The clients list is available throughout CommandHandler.

Want to do the same thing with a Dictionary created in TcpServer:

private readonly Dictionary<string, IClient> connectedClients = new Dictionary<string, IClient>();

In CommandHandler:

private Dictionary<string, IClient> connectedClients;

public void Setup(Dictionary<string, IClient> connectedClients)
        {
            this.connectedClients = connectedClients;
        }

connectedClients is alway null

What am I doing wrong here?

Help with Xamarin app consuming new Core API

$
0
0

I have an Xamarin app in Beta testing.  In the production environment it connects to a WCF service with a poorly-written back-end.  I am now writing a Core API for a new back-end (for the app and other new clients I will write).  I would like to test my Web API using my Xamarin app in a development environment (VS 2017).  My Core API works with Postman, but how do I host my API on my development box in such a way that my Xamarin app can consume it?  In my research I have found info on consuming a web api from Xamarin which would allow me to test my Xamarin app on a deployed Web API.    But I don't know how to consume the API that I wrote myself and is still in development.

Using CreatedAtAction with NSwag/OpenAPI generated controller

$
0
0

I want to use CreatedAtAction to return an HTTP 201 to the client with the correctLocation header, but I'm doing it from a class and namespace different than the actual controller. This is because I'm usingNSwag to generate a controller from an OpenAPI 2 spec, which generates the actual controller and an interface to implement the logic for the controller in, which I inherit from. It is in this child class that I'm trying to use CreatedAtAction with nameof to ensure that if I change the name of the action in the OpenAPI spec that it results in errors that the compiler can help track down.

The issue is that I can't seem to find the right combination of nameof to use withCreatedAtAction to get a 201 out of it; instead it errors with HTTP 500: "InvalidOperationException: No route matches the supplied values." I've looked around for this error and I haven't found anyone trying to useCreatedAtAction with an action pointing to a different namespace and class; only within the same namespace. Usually this issue surfaces when the get action referenced doesn't exist, but mine does exist, just on a different class.

More concretely, I use an OpenAPI spec file with NSwag to generate something like the following code (omitting unrelated methods):

//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v12.0.15.0 (NJsonSchema v9.13.22.0 (Newtonsoft.Json v11.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Project.Controllers.Generated
{
    #pragma warning disable

    [System.CodeDom.Compiler.GeneratedCode("NSwag", "12.0.15.0 (NJsonSchema v9.13.22.0 (Newtonsoft.Json v11.0.0.0))")]
    public interface IThingController
    {    
        Task<ActionResult> CreateParametersAsync(ThingParameters parameters);
        Task<ActionResult<ThingParameters>> GetParametersAsync(int id);
    }
    [System.CodeDom.Compiler.GeneratedCode("NSwag", "12.0.15.0 (NJsonSchema v9.13.22.0 (Newtonsoft.Json v11.0.0.0))")]
    [Microsoft.AspNetCore.Mvc.Route("api/thing/selection")]
    public partial class ThingController : ControllerBase
    {
        private IThingController _implementation;
        public ThingController(IThingController implementation)
        {
            _implementation = implementation;
        }
        [Microsoft.AspNetCore.Mvc.HttpPost, Microsoft.AspNetCore.Mvc.Route("parameters")]
        public async Task<ActionResult> CreateParameters([Microsoft.AspNetCore.Mvc.FromBody] ThingParameters parameters)
        {
            return await _implementation.CreateParametersAsync(parameters);
        }
        [Microsoft.AspNetCore.Mvc.HttpGet, Microsoft.AspNetCore.Mvc.Route("parameters/{id}")]
        public async Task<ActionResult<ThingParameters>> GetParameters(int id)
        {
            return await _implementation.GetParametersAsync(id);
        }
    }

    #pragma warning restore
}

I then implement the interface (omitting all unrelated methods):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using Project.Controllers.Generated;

namespace Project.Controllers
{
    public class ThingDataController : ControllerBase, IThingController
    {
        public async Task<ActionResult> CreateParametersAsync(Project.Controllers.Generated.ThingParameters parameters)
        {
            Model.ThingParameters newParameters = Convert(parameters);
            if (!ValidlyOverlaps(repository.List(), newParameters))
            {
                return BadRequest();
            }

            int id = repository.Create(newParameters);
            return CreatedAtAction(nameof(ThingController.GetParameters), nameof(ThingController), new { id }, parameters);
        }

        public async Task<ActionResult<Project.Controllers.Generated.ThingParameters>> GetParametersAsync(int id)
        {
            Model.ThingParameters settings = repository.Retrieve(id);
            if (settings == null)
            {
                return NotFound();
            }

            return Ok(Convert(settings));
        }
    }
}

And I connect the implementation to the generated controller in Startup.ConfigureServices viaservices.AddTransient<IThingController, ThingDataController>();

Stepping through the code under the debugger confirms that it gets to the CreatedAtAction line, so since there's no application logic there I'm guessing ASP.NET Core is barfing on the arguments I'm providing.

Visual Studio 2017 warns me that it can't resolve the controller or action in thenameof expressions. I've tried fully qualifying the names but that gives the same error. I've also tried replacing thenameof expressions with raw strings of both the controller name and the fully qualified controller name to see if that would work but it gives the same error. The full exception in the HTTP 500 response is:

System.InvalidOperationException: No route matches the supplied values.
   at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsync(ActionContext context, ObjectResult result)
   at Microsoft.AspNetCore.Mvc.ObjectResult.ExecuteResultAsync(ActionContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

What is the correct thing to put in the nameof arguments to the CreatedAtAction in this case?

I'm using ASP.NET Core 2.1.2 with NSwag.MSBuild 12.0.15, targeting Linux running .NET Core under Docker using the official ASP.NET Core base images.

How to get a file from server machine (but not in root folder)

$
0
0

Hi all,

My server is under C:\inetpub\wwwroot\MyWebsite folder in servermachine

however I need to show a pdf file from that machine's another folder

C:\MyFiles\MyPDFs\MyPDF.pdf

Is it possible to reach that file? or make shortcut of it into my publish folder or something?

Razor Components as a library included in MVC project

$
0
0

I would like to pack my custom Razor Components as a library and add that to my ASP.NET Core MVC project. How to do that so that the components render correctly in my Views provided through Controllers?

I have tried the following:

  • Create a Razor Class Library, add Microsoft.DotNetCore.Components package, add reference of that lib to MVC project
  • Create Razor Components project and reference it in my MVC project
  • Add MVC to Razor Components and try to integrate both. I have ended with both "projects" side by side, but was unable to render components in Views

Thank you in advance for help :-)

Which publish method is preferable

$
0
0

Hi all,

I have windows 10 installed work station and I am planning to use a bigger server machine in the future but again with windows 10 in it.

What I want to ask is; Which publish method is preferable considering performance, reliability and other reasons. I meant Framework dependent and Self contained / Portable combinations you know...

thank you.

Connecting to SOAP(ASMX) service with .NET Core 2.0 --Error importing

$
0
0

When I try to add a reference of a web service to my .Net Core project, I get an error "Error importing wsdl: binding on which depends wsdl: port.
XPath to wsdl: binding".
but if the web service is WCF no. I'm missing some package?


How do I deploy my asp.net core webapp on my client system

$
0
0

Dear All,

I just built a point of sale application for my client. The client part of the application is built with JavaFx and the web service is bulit with asp.net core.

I am 97 % done with the project. I would be deploying the project at the client system very soon.

Please what do I need to do to ensure that my asp.net core web service server fruns on my clients server computer.

The database was built on microsoft sql server. What dependencies do I need to install on the clients system.

Thanks alot.

beginner level question on how to debug javascript in Core and Visual Studio 2017

$
0
0

I think I am missing something fundamental and basic in my attempts to set a breakpoint in my dot net core app.

I use F12 in Google, select sources and set a breakpoint, but it doesn't behave as I expect/hope.

It will sometimes break on the spot I select, but most often it will stop near the spot I want, but it is as if it has the wrong code loaded.  Then a message appears that I am debugging to push F10, and F10 leads to a util.js file.  And then when I push F5 it will break some other place in the bootstrap or js file.

Also, when I attempt to load a page a second time, it will just hang and take a LONG time to finish loading. (several minutes)

I have four breakpoints set in my javascript function, one near the beginning and the rest spread out across it.  The only one it ever stops at (when it does) is the very last one.  There is not a code path to get to the last one, without passing the others, but it only stops on the one.

Sometimes (not very often) it will break on the code in Visual Studio that seems to be about the same spot as the place I set the breakpoint in Chrome.  But no values are available for inspection.

What am I doing wrong?  

asp.net core

$
0
0

Hello,

I am new to this forum.I've been a .net developer for 15 years, but exclusively on desktop applications and vb.net.I spent 11 years in the same little company without having taken a training course, if it was not my personal skills to search the network.Now, I am in charge of the new project that needs to be written in the asp.net core.I do not know anything about this technology.So I'm in a panic looking for the mass of information on the web.I do not know anything about C #, jQuery, angular, etc.Is there a good way to start?I am just alone and I would like some help without criticism of my situation.I am really in love with my job (a little less of my company).It's a shame to think that the best way is to change and do something else. Please help...

.Net Core: replace AzMan

$
0
0

Hi all,

I have a bunch of WCF services on the same project, and I have a cross-cut module that loads an AzMan XML file which validates against user permissions, based on Active Directory roles.

However the architecture of my platform is evolving to .Net core, and services are sort of being replaced by APIs.

I would like to have some sort of new authorization module, cross-cut to all APIs, which may be ASP.Net Core MVC projects on premisses, on Azure or even azure functions.

I'm aware that for example functions have a different way for authentication/authorization, but is there any out of the box solution/API/Framework that I could use to replace AzMan?

The closest thing I found out is using custom policies in ASP.Net core, not sure if is the right way.,..

aspnet core and websocket limitations

$
0
0

Hi all, 

I am building an ASP.NET Core Websocket, using simple plain websocket integration. I also have a console app for load testing the websocket server. Creating ClientWebsocket connections work fine up until 5000. And it is always the 5000 limit. The next request doesnot reach the server, so might be an issue in the console app, or the request being blocked.

Any clues?

regards,

Riccardo

Viewing all 9386 articles
Browse latest View live


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