basic Authentication in .net framework 2.0
I need help in asp .net, I want to read the username from the HTTP header in .net framework 2.0. (like we do in basic authentication) Is there a way to do that? Thanks in advance.
P.S: I know it's old but need to do it.
See also questions close to this topic
-
Filter items in a listbox that have been added with json
Well I'm trying to list items that are from listbox created with UserControl and the text properties are defined with a json file.
This is my .json file:
{ "Games": { "Quantity": 2, "Title0": "SomeGame1", "Description0": "Fps game", "Image0": "Some image link", "Link0": "GameStore.com/Somegame1", "Title1": "SomeGame2", "Description1": "RPG game", "Image1": "Some image link", "Link1": "GameStore.com/Somegame2", } }
This is the code to load the games as items in the listbox:
string JsonFile = Environment.CurrentDirectory @"\Test.json"; dynamic jasonfile = JsonConvert.DeserializeObject(JsonFile); GameUserControl[] Games = new GameUserControl[jasonfile["Games"]["Quantidade"]]; for (int quantity= 0; quantity < Games.Length; quantity++) { Games[quantity] = new GameUserControl(); Games[quantity].Descrição.Content = (jasonfile["Games"]["Title" + quantity]); Games[quantity].jog = (jasonfile["Games"]["Titulo" + quantity]); Games[quantity].lin = (jasonfile["Games"]["Link" + quantity]); string image = jasonfile["Games"]["Image" + quantity]; Games[quantity].imag = new ImageBrush(new BitmapImage(new Uri(image, UriKind.Absolute))); GamesListBox.Items.Add(Games[quantity]); }
This is the code I used in a textbox to try to filter:
if (CollectionViewSource.GetDefaultView(GamesListBox.Items) != null) CollectionViewSource.GetDefaultView(GamesListBox.Items).Filter = (o) => { return o.ToString().ToLower().Contains(Search.Text.ToLower()); };
But it didn't work, the item names are always GameUserContro.Can someone help me?
-
Advantage of .Net Core over WCF for RESTful APIs
We are currently using WCF to create RESTful APIs, it is working fine and has an added advantage that it can be consumed via SOAP too if we ever need to. We have all our systems using Microsoft technologies.
There is no active development on WCF but the current functionality is working fine for us. However, I believe the recommended approach is to start using .Net core for RESTful services. What are the additional advantages .Net core offers over WCF (apart from being platform independent)?
-
Generic class type constraint with a generic class having another constraint
Let's say I have a generic class
public class G<T> { }
and I want to declare final class as
public class F<T> where T : G<T> { }
that seems to be possible, but what if I want to complicate the task and add a constraint to the class G like that
public class A { } public class DA : A { } public class DB : A { } public class G<T> where T : A { }
and finally I want to do this
public class F<T> where T : G<T> { }
that does not work, it says T has to be of type A which is understandable and it looks like I can rewrite it like this
public class F<T, U> where T : G<U> where U : A { }
but in this case the usage has a redundant declaration
public class DF : F<G<DA>, DA> { }
I have to repeat DA twice when using class F even though it is quite clear if I use G as a generic type the generic type of G is DA. Is there a way to avoid this redundancy?
-
Cascading databound <ajaxtoolkit:combobox> and <asp:dropdownlist> in asp.net
I have an
asp.net
search form that includes anajaxToolkit Combobox
and a standardasp DropDownList
. Both controls are bound to two separatedSqlDatasource
components.Something like this:
<ajaxToolkit:ComboBox ID="cbConvenzionato" runat="server" AutoCompleteMode="SuggestAppend" DropDownStyle="DropDownList" DataSourceID="sdsConvenzionati" DataTextField="nome" DataValueField="id" AutoPostBack="true" OnSelectedIndexChanged="cbConvenzionato_SelectedIndexChanged" /> <asp:DropDownList ID="ddlVeicoli" DataSourceID="sdsVeicoli" DataTextField="targa" DataValueField="id" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlVeicoli_SelectedIndexChanged" AppendDataBoundItems="true"> <asp:ListItem Text="TUTTI" Value="" Selected="True" /> </asp:DropDownList> <asp:SqlDataSource ID="sdsConvenzionati" runat="server" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, nome FROM anag_convenzionati ORDER BY nome;" /> <asp:SqlDataSource ID="sdsVeicoli" runat="server" EnableCaching="false" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, targa FROM veicoli_contratti WHERE ((@id_convenzionato IS NULL) OR (id_convenzionato = @id_convenzionato)) ORDER BY targa;"> <SelectParameters> <asp:ControlParameter Name="id_convenzionato" ControlID="cbConvenzionato" PropertyName="SelectedValue" Direction="Input" ConvertEmptyStringToNull="true" DbType="Int32" DefaultValue="" /> </SelectParameters> </asp:SqlDataSource>
There's also a third
sqldatasource
(sdsNoleggi
) that feeds agridview
but this's not a problem right now.In code behind I have two event handlers:
protected void cbConvenzionato_SelectedIndexChanged(object sender, EventArgs e) { sdsVeicoli.Select(DataSourceSelectArguments.Empty); Search(); } protected void ddlVeicoli_SelectedIndexChanged(object sender, EventArgs e) { Search(); } private void Search() { sdsNoleggi.Select(DataSourceSelectArguments.Empty); }
I tought in this way I should filter
ddlVeicoli
items after selecting an item incbConvenzionato
... but it's not working... why?If I look into
sdsVeicoli
SelectParameters
in debug I can seeid_convenzionato
being correctly set to selected value (id coming fromcbConvenzionato
) I bet also thatsdsNoleggi
dataset wiil be correctly updated with new values since I did this many times before. So why bound control it's not? I tried also to force addlVeicoli.DataBind()
aftersdsVeicoli.Select()
call ... but this had no effect. -
Swagger UI not working for REST API (asp.net web api2) application
I have asp.net mvc project with .NET Framework 4.7.2 and the same project contains asp.net web api2 controller in a separate folder : Controllers. The solution is legacy. The API are already in use in the PRODUCTION environment. Now I added the Swagger nuget package (Install-Package Swashbuckle -Version 5.6.0) to this existing project. Post that I see a SwaggerConfig.cs added to the App_Start folder of the Solution Explorer.
Here the asp.net mvc controllers are used by App1 pointing to the server: www.app1.com and asp.net web api2 controllers are used by another frontend angular app: App2 pointing to the server : www.app2.com
The complete deployment package for both App1 and App2 are hosted in IIS
Any request related to App1 is handled by www.app1.com and any api request related to App2 (Angular frontend) is handled by App1 only using IIS Rewrite rules at App2 level which redirect any api request to App1 only.
Now in this case when I tried to navigate to www.app1.com/swagger , I see it is loading the SwaggerUI for me, but when I tried to navigate to www.app2.com/swagger it is not working and instead of that it is loading the Angular frontend application
Here goes the App1 and App2 at IIS level:
Can anyone help me here by providing their guidance to fix this issue?
-
Cors error missing allow origin header. MailKit
I have
cors error missing allow origin header
error only on ONE post request. My CORS Policypublic void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
Every request work fine, but one POST request fails, it's really weird. Code in controller action which failed use MailKit and SMTP to send email, maybe that's cause
-
Bing API is responding with timeout often - c#
Implemented a azure function batch job.. API responded well when I send 10000 record .. when sending 100000 records(sending it as a batch of 500) API stops responding..
Firstly , I was getting timeout error.. after some time , it stops responding..
API is working well in browser or when I debug by sending 10 records ..
-
Xero Authorization Cancel in ASP.NET
public async Task Callback(string code, string state) { try { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider(); var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>(); string ClientID = state.Split(',')[0]; string CompanyID = state.Split(',')[1]; string ClientSecret = string.Empty; DataTable dt = objIntegration.GetIntegrationCompanyDetail(ClientID, CompanyID); if (dt.Rows.Count > 0) { XeroConfiguration XeroConfig = new XeroConfiguration { ClientId = ClientID, ClientSecret = dt.Rows[0]["ClientSecretKey"].ToString(), CallbackUri = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]), Scope = ConfigurationManager.AppSettings["XeroScope"], State = ClientID + "," + CompanyID }; var client = new XeroClient(XeroConfig, httpClientFactory.CreateClient()); var xeroToken = (XeroOAuth2Token)await client.RequestAccessTokenAsync(code); List<Tenant> tenants = await client.GetConnectionsAsync(xeroToken); Tenant firstTenant = tenants[0]; string serializedXeroToken = JsonConvert.SerializeObject(xeroToken); objIntegration.UpdateIntegrationDetail(CallbackResonse.Tenants[0].TenantId, CallbackResonse.AccessToken, CallbackResonse.RefreshToken, CallbackResonse.ExpiresAtUtc, serializedXeroToken, ClientID, CompanyID); System.Web.HttpContext.Current.Response.Redirect(ConfigurationManager.AppSettings["XeroSuccessUri"]); } } catch (Exception ex) { } }
here this is my code if i am giving cancel in xero authorization it throw No HTTP resource was found that matches the request URI 'https://localhost:/api/Xero/Callback?error=access_denied&state=1B5D7F8C60534E19BC91E3919357B5B1,323'. how to rectify this problem
-
Web API - Need a way to return Multipart Form data in response
I am currently building a web service to replace one of the legacy application and the web service response has to be matching to the existing service. I am currently using .Net 5.0 Core ASP.Net web API.
The request format for the service is
/DocuemntService?info&pVersion=0046&contRep=Z8&docId=%7BDCC15450-79FE-45BF-AC73-250544C8F8EE%7D&accessMode=r
Response Expected : This was the raw output captured from legacy service (Note this only returns document info in headers and not the document)
HTTP/1.0 200 OK
X-DocServiceInfoS: RSP-ID -431702117 begin
Connection: close
Date: Fri Jan 29 15:15:25 WST 2021
Server: Document Service - HTTP Interface/1.0.0
Content-Length: 258
Content-Type: multipart/form-data; boundary=NEXT_COMPONENT
X-dateC: 20160120
X-timeC: 034143
X-dateM: 20160120
X-timeM: 034143
X-numComps: 1
X-contRep: Z8
X-docId: {DCC15450-79FE-45BF-AC73-250544C8F8EE}
X-docStatus: online
X-DocServiceInfoE: RSP-ID -431702117 end
--NEXT_COMPONENT
Content-Length: 0
Content-Type: image/tiff
X-Content-Length: 54138
X-compId: data
X-compDateC: 20160120
X-compTimeC: 034143
X-compDateM: 20160120
X-compTimeM: 034143
X-compStatus: online
X-pVersion: 0045
--NEXT_COMPONENT--
So far I used the following code from Controller to return the multipart form data, but it pushes json file and it doesnt return anything similar to above.
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet] public async Task<HttpResponseMessage> DocumentServer([FromQuery] DocumentInfoRequest requestInfo) { HttpResponseMessage ApiResponse= new HttpResponseMessage(HttpStatusCode.OK); IQueryCollection queryStringParams = ControllerContext.HttpContext.Request.Query; Response.ContentType= if (Request.Query.Keys.Count > 0) { //First query parameter determines the operation String operation = queryStringParams.Keys.First(); switch (operation) { case "serverInfo": ApiResponse=await ServerInfo2(requestInfo, ApiResponse); break; case "info": DocumentInfo doc = DocumentInfo(requestInfo, Response); Response.Headers.Add(AppConstants.XCSINFOS_BEGIN); Response.Headers.Add(AppConstants.DATE); Response.Headers.Add(AppConstants.XCSINFOS_END); using (MultipartFormDataContent multipartForm = new MultipartFormDataContent("NEXT_COMPONENT")) { multipartForm.Headers.Add("X-docId", requestInfo.DocId); multipartForm.Headers.Add("X-compId", doc.CompId); Response.Headers.Add(new KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>("X-docId", requestInfo.DocId)); Response.Headers.Add(new KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>("X-compId", doc.CompId)); await WriteData(Response, "Test"); ApiResponse.Content = multipartForm; }; break; case "get": await DownloadDocument(requestInfo, Response); break; case "create": break; } } return ApiResponse; }
I am not sure whether I am following the right approach? The above code is only sample to see whether it returns few parameters and if it works my plan is to develop to return all document info and in the Get request, return the document itself.
I primarily have the java background and tried to implement this in Web API because .Net is preferred for this application deployment.
I already wasted quite a lot of time on this and I couldn't find any relevant article to solve this problem.
Any help or direction would be much appreciated?
Thanks