HttpClient keeps conversting HTTP calls to HTTPS
I have the following code in a Blazor Page (.razor.cs) to load some data from a sample API.The API URL that is pointed to a non https endpoint since there is no https version of the same.
protected async Task LoadData()
{
string APIURL = "http://universities.hipolabs.com/search?country=United+States";
// create request object and pass windows authentication credentials
var request = new HttpRequestMessage(HttpMethod.Get, APIURL);
request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);
// send the request and convert the results to a list
var httpResponse = await client.SendAsync(request);
}
But the browser is calling the https version always and this leads to an error
I have inspected program.cs file and have removed app.UseHttpsRedirection()
,still the same issue.I'm not sure if this affects external api call as it only configures the request processing pipeline as per my understanding.
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
Fluent Validation with conditions in asp.net core
I am working in asp. net core 6.0 web API project (clean architecture (CQRS)).
I am using fluent validation for validate command and queries.
public class CreateSiteDestinationSectionsCommand : IRequest<x> { public int DestinationSectionId { get; set; } public int DestinationSectionTitleId { get; set; } public int SiteCodeId { get; set; } public string Description { get; set; } public List<DestinationImageDto> Images { get; set; } public List<string> Links { get; set; } }
This is i did inside CreateSiteDestinationSectionsCommandHandler.
var DestinationSectionTitleId = request.DestinationSectionTitleId; if (DestinationSectionTitleId != 10) { if (DestinationSectionTitleId == 1 || DestinationSectionTitleId == 2 || DestinationSectionTitleId == 5 || DestinationSectionTitleId == 7 || DestinationSectionTitleId == 8 || DestinationSectionTitleId == 9 || DestinationSectionTitleId == 11) { var sectionimageCount = request.Images.Count; if (sectionimageCount != 1) { throw new ApiValidationException("Section has not more than one image"); } else (DestinationSectionTitleId == 10 && request.Images != null) { var sectionimageCount = request.Images.Count; if (sectionimageCount != 0) { throw new ApiValidationException("Section doesnot have any image"); } } } }
But instead of handling validation inside commandHandler, I have to handle validation in CreateSiteDestinationSectionsCommandValidator.
I tried this,
RuleFor(x => x.Images) .Must(x => x != null) .When(x => x.DestinationSectionId != 10) .WithMessage("Site Section image required"); RuleFor(x => x.DestinationSectionId).NotEmpty(); RuleFor(x => x.Images) .Must(x => x.Count != 1) .When(x => x.DestinationSectionId == 1 && x.DestinationSectionId == 1 && x.DestinationSectionId == 2 && x.DestinationSectionId == 5 && x.DestinationSectionId == 7 && x.DestinationSectionId == 8 && x.DestinationSectionId == 9 && x.DestinationSectionId == 11 ) .WithMessage("Site Section has not more than one image"); }
When I check throug postman request, Even I send with DestinationSectionId = 10 (and not sending any images), I got validation error as
"errors": { "Images": [ "Site Section image required" ] }
And Even I send more than 1 images for DestinationSectionId = 1, I did not get validation error. BUT I shoud get validation error as
Site Section has not more than one image
Why this validations not work correctly? What I missed?
-
Using RestSharp to request a file fails with memory issue
I have to API's talking to each other on Kubernetes. The first API asks the second API for a small file using RestSharp (in ASP.NET). The file is 8Kb so basically not large at all.
Yet i get the following message on the API that wants to receive the file:
Exception of type 'System.OutOfMemoryException' was thrown. at RestSharp.RestClient.ThrowIfError(RestResponse response) at RestSharp.RestClientExtensions.GetAsync(RestClient client, RestRequest request, CancellationToken cancellationToken) at Aftermarket.Server.AdministrationService.Server.Services.Services.RunSessionService.DownloadRunSession(String foldername) in /src/Aftermarket.Server.DbApi/Server/Services/Services/RunSessionService.cs:line 59
The code U use to call the other API and ask for the file looks as follows:
public async Task<byte[]> DownloadRunSession(string foldername) { try { var request = new RestRequest($"{config["WebApiServer:WebApiServerUrl"]}/blob/{foldername}"); var response = await client.GetAsync(request); if (!response.IsSuccessful) { Console.WriteLine("File download failed"); Console.WriteLine(response.StatusCode); return null; } return response.RawBytes; }catch(Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return null; } }
The API that responds by sending the file has the following controller method:
public IActionResult GetBlob([FromQuery] string folderName, [FromServices] GetBlobsService _getBlobsService) { _logger.Info(folderName); Guid guid = Guid.NewGuid(); if (_env.EnvironmentName == "dev" || _env.EnvironmentName == "prod") { byte[] blob = _getBlobsService.GetBlob(folderName, guid, _logger); if (blob == null) return this.NotFound(); else { return File(blob, "application/force-download", guid + ".zip"); } } else { return Content("This function is only available in Dev/Uat Environment"); } }
Any one have any idea how a 8Kb file is causing this issue?
-
How is Windows Authentication Wired Up?
I'm in the process of creating an ASPNET Core 6 MVC app in VS 2022 which will eventually be deployed in a Docker container. Windows Authentication will be used as it's an internal app. When creating this project from scratch with File -> New Project -> ASP.NET Core 6 Web App (Model-View-Controller) and with Windows Authentication enabled, everything works as expected.
This is where it gets weird. Since this will be a Docker container on Linux, I commented out the IIS settings in launchSettings.json.
{ //"iisSettings": { // "windowsAuthentication": true, // "anonymousAuthentication": false, // "iisExpress": { // "applicationUrl": "http://localhost:60583", // "sslPort": 44391 // } //}, "profiles": { "ASPNETCORE6": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "https://localhost:7276;http://localhost:5276", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
To recreate this issue, comment out the following from the generated Program.cs file:
//using Microsoft.AspNetCore.Authentication.Negotiate; //builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) // .AddNegotiate(); //builder.Services.AddAuthorization(options => //{ // options.FallbackPolicy = options.DefaultPolicy; //}); //app.UseAuthentication(); //app.UseAuthorization();
Now, when I run a debugging session using IIS Express, the browser windows renders with my correct domain name being displayed. How is this even possible? Is something being cached? Also, the browser is going to http://localhost:44391/ when debugging with IIS Express even though this is commented out in launchSettings.json.
Note: Windows authentication is not working when I debug with Kestrel, which is what I would expect.
-
Blazor Webassembly Prerendering: How to avoid HeadContent render two times
I have a Blazor WASM prerendered .NET6 application.
In Index.razor on the Hosted server project, I have a component that loads css files dynamically.
The problem is that the files are rendered two times causing the page to lose and reapply the css for a moment, very noticeable with slow connections.
<HeadContent> @foreach (var style in Template.CssRepository) { <link rel="stylesheet" href="@style"> } </HeadContent>
I would like the styles to be prerendered an not reloaded again when the app is "ready".
The Template object state is already persisted using ApplicationState.TryTakeFromJson<>, but HeadContent reload itself recalling all Css files.
I tried using OnAfterRender method but when it fires the css files have already been loaded twice.
-
How to avoid repeating a value in a data binding within a foreach loop?
I have a problem I am doing a questionnaire, in a list of questions I get all the questions stored in the database, then I iterate that list with a foreach loop, and for each question I put an input text , in each input text I use the bind- value and there I put the value of my object like this:
@bind-value="Respuesta.ValorRespuesta"
but when doing this the response that is put in the input text is repeated because I am using data binding , so how can I do so that it does not give me the same value but a different one for each response that is answered
this is my code:
@foreach (var item in ListadePreguntas) { <input type="text" id="respuesta" class="form-control form-control-sm" placeholder="Respuesta" @bind-value="Respuesta.ValorRespuesta" /> } @code{ public Respuesta Respuesta { get; set; } = new Respuesta(); }
As you can see, my response values are repeated due to the use of data binding, how can you avoid this, how can you perform a databinding that has different values?
-
Blazor TypeError
Blazor application throws error whenever i try to call methods in api. I've tried different httprequest methods but nothing changed so far, still struggling to call api methods.
Error message: Unhandled exception rendering component: TypeError: Failed to fetch System.Net.Http.HttpRequestException: TypeError: Failed to fetch at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken) at System.Net.Http.Json.HttpClientJsonExtensions.d__9
1[[System.Collections.Generic.List
1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext() at blazor.Pages.TableDesign.OnInitializedAsync() in C:\Users\Pc\source\repos\blazor\blazor\Pages\TableDesign.razor:line 124 at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync() at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)This is the api method which i'm trying to call:
namespace Api.Controllers{ [ApiController] [Route("api/[controller]/[action]")] [HttpGet] public IActionResult GetColumns() { SqlConnection con = new SqlConnection(connection); SqlDataAdapter adp = new SqlDataAdapter("select*from dynamicTable",con); adp.SelectCommand.CommandType = CommandType.Text; DataTable dt = new DataTable(); con.Open(); adp.Fill(dt); foreach (var item in dt.Columns) { colList.Add(item.ToString()); } con.Close(); return Ok(colList); }
Blazor http request
List<string> colNames = new List<string> (); protected override async Task OnInitializedAsync() =>colNames= await Http.GetFromJsonAsync<List<string>>("https://localhost:5001/api/table/GetColumns"); ```