413 Request Entity Too Large For HttpClient - asp.net-web-api

Once i send the HttpClient request through the PostAsJsonAsync i get the response as Request Entity too large. but i can directly call to webapi and send the request and returns a successfull response. but through the PostAsJsonAsync it returns the 413 error code.
This is my code
var client = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings.Get("API_HOST")) };
const string api = "CmSaveChange" + "/" + "SaveChange";
var response = client.PostAsJsonAsync(api, entity).Result;
var retunValue = response.Content.ReadAsAsync<HybridDictionary>().Result;

The problem has to be solved on the server-side (self hosting HttpSelfHostServer or IIS).
The buffers have to be set to a higher value.
If the host run's under IIS:
Configure IIS
If the server is running as HttpSelfHostServer:
You have to set higher values (as needed) to the config parameters.
Example for vb.net
Dim cSelhostConfiguration As String = cIPADressePort
' Note: cIPADressePort contains the IP address and port on which the host is listen
Dim config As New HttpSelfHostConfiguration(cSelhostConfiguration)
'Set here the needed size (in bytes)
config.MaxBufferSize = 250000000
config.MaxReceivedMessageSize = 250000000
'
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
'
Using server As New HttpSelfHostServer(config)
Try
server.OpenAsync().Wait()
Console.WriteLine("")
Console.WriteLine("WebService started... ")
Console.WriteLine("Waiting for work...")
Catch aggEx As AggregateException
Console.WriteLine("Error loading Server")
End Try
Console.WriteLine()
Console.WriteLine("Press enter to close the server")
Console.ReadLine()
End Using

Related

Connect to Azure Storage blob Behind Proxy: The proxy tunnel request to proxy 'http://ipaddress:port/' failed with status code '407'

Follow code available on Microsoft documentation portal but what if I want add the proxy to it? I'm using .NET Core 6+
string blobstorageconnection = pConfig.AzuerBlobStorageConnectionString;
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
CloudBlobClient? blobClient = null;
CloudBlockBlob? blockBlob = null;
blobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(pConfig.AzureStorageContainerName);
blockBlob = container.GetBlockBlobReference(pFileName);
await blockBlob.UploadFromFileAsync(pFilePath + #"\" + pFileName);
I tried above code and it is working fine without proxy setting in network but as we enable the proxy setting system raise the error : "The proxy tunnel request to proxy 'http://ipaddress:port/' failed with status code '407'."

Getting empty response from Microsoft Graph API Authorization Requst?

I am getting an empty response Microsoft Graph API although the status of request is 200.
I have been following this documentation. - https://learn.microsoft.com/en-us/graph/auth-v2-user
I successfully registered an app and got the ClientID.
I am using VBScript to create a GET Request - here is my code:
Dim oXMLHTTP
Dim oStream
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=######&response_type=code&response_mode=query&scope=offline_access+mail.read", False
oXMLHTTP.Send
wscript.echo oXMLHTTP.status
wscript.echo oXMLHTTP.responseBody
Can anyone advise on what I am doing wrong?
oXMLHTTP.status = 200
The process of using oauth code flow to obtain tokens and call api is as follows:
Enter this link in the browser to obtain the authorization code:
https://login.microsoftonline.com/{tenant id}/oauth2/authorize?
client_id={your-client-id}
&response_type=code
&redirect_uri=https://localhost:4500/web/completeoauth/ms
&response_mode=query
&scope=openid offline_access https://graph.microsoft.com/mail.read
&state=12345
Use code to get access token: here.
For your question, it is recommended that you use MSAL.NET for authentication, which eliminates the step of obtaining code.
Private Function Login() As Boolean
Dim publicClientApp As IPublicClientApplication
publicClientApp = PublicClientApplicationBuilder.Create(client_id).WithAuthority(authority).Build()
Dim accounts As IEnumerable(Of IAccount) = publicClientApp.GetAccountsAsync().Result()
Dim firstAccount As IAccount = accounts.FirstOrDefault()
Dim authResult As AuthenticationResult
Try
authResult = publicClientApp.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync().Result()
Catch e As MsalUiRequiredException
Try
authResult = publicClientApp.AcquireTokenInteractive(scopes).ExecuteAsync().Result()
Catch ex As Exception
'user cancelled
Return False
End Try
Catch ex As Exception
Console.WriteLine($"Auth Exception: {ex.Message}")
Return False
End Try
_accessToken = authResult.AccessToken
Return True
End Function
Please see:VB.NET – USE MSAL.NET IN A CONSOLE APPLICATION TO AUTHENTICATE TO AZURE

Minio Received non-HTTP message from new connection

server error:
Received non-http message from new connection
client error:
code:
var endpoint = "127.0.0.1:9000";
var accessKey = "MFQD47M******R5TZ1";
var secretKey = "WsuNQtYs********npA7iMRLjRmx";
var minio = new MinioClient(endpoint, accessKey, secretKey).WithSSL();
await minio.ListBucketsAsync();
Try removing .WithSSL(). It seems like your server is expecting plain HTTP, but your client is expecting HTTPS. First try changing the client to plain HTTP. If that works, you'd probably want to properly enable HTTPS on your server so you have a secure connection.
https://docs.minio.io/docs/how-to-secure-access-to-minio-server-with-tls

System.OutOfMemoryException when uploading a large file (~600MB) using .NET 4.0 & HttpClient

I am getting this error only on my local workstation and prod server.
In Dev and Cert it is working fine.
local workstation - 20 GB memory, Win 7 64 bit, IIS Express, VS
2013 dev, cert & prod - 8 GB memory , 2008 R2 64 Bit, IIS 7.5
I have a web api (.net 4.0) which takes the incoming request body and uploads it to a storage server. configured web api as per this website.
I have these in my web.config
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
<system.web>
<httpRuntime maxRequestLength="2097152" />
</system.web>
I also have an implementation of IHostBufferPolicySelector which returns false for PUT & POST requests. so the request to this web api for PUt & POST are not buffered.
for any files < ~350 MB it is working fine. but web api is throwing out of memory exceptions when file size >= ~ 400 MB and this is happening only on Local workstation and Prod server.
Web Api controller calls below code to stream the request to the destination server
public async Task<HttpResponseMessage> StoreObjectAsync(Uri namespaceUrl, string userName, string password, string objectName, Stream objectContent, string contentType = "application/octet-stream", IDictionary<string, string> systemMetadata = null)
{
Uri namespaceRootUrl = Utilities.GetNamespaceRootUrl(namespaceUrl);
using (var request = new HttpRequestMessage() { Method = HttpMethod.Put })
{
request.RequestUri = Utilities.CreateRequestUri(namespaceRootUrl, objectName);
request.Content = new StreamContent(objectContent);
request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
HttpResponseMessage response;
response = await this.httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
return response;
}
}
After doing some research online, i understand from this link & this link that HttpClient on .Net 4.0 buffers the request body and because of that behavior it seemed to me that it is throwing outofmemory exception
so I changed my code to below this time using HttpWebRequest using which I have the control to specify that request should be streamed but not buffered.
public async Task<HttpResponseMessage> StoreObjectAsync(Uri namespaceUrl, string userName, string password, string objectName, Stream content, long contentLength, string contentType = "application/octet-stream", IDictionary<string, string> systemMetadata = null)
{
Uri namespaceRootUrl = Utilities.GetHCPNamespaceRootUrl(namespaceUrl);
HttpWebRequest httpWebRequest = ((HttpWebRequest)WebRequest.Create(requestUri));
httpWebRequest.Method = "PUT";
httpWebRequest.KeepAlive = true;
httpWebRequest.AllowWriteStreamBuffering = false;
httpWebRequest.ContentType = contentType;
httpWebRequest.ContentLength = contentLength;
using (Stream requestStream = await httpWebRequest.GetRequestStreamAsync())
{
await content.CopyToAsync(requestStream);
}
var webResponse = await httpWebRequest.GetResponseAsync();
HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;
Stream httpWebResponseContent = httpWebResponse.GetResponseStream();
HttpResponseMessage response = new HttpResponseMessage()
{
StatusCode = httpWebResponse.StatusCode,
ReasonPhrase = httpWebResponse.StatusDescription,
Content = new StreamContent(httpWebResponseContent)
};
return response;
}
Now it is working fine on my local machine. I am able to upload files around 1GB without any errors or memory exceptions. Havent pushed this to Prod yet.
But I still dont understand why the same code using HttpClient on .net 4.0 worked on Dev and Cert servers but not on Prod and my local.
please help me in understanding
How to find out why it worked on Dev and Cert? What system/server
configurations will affect the memory allocations to this api?

401 error with urbanairship using httpsurlconnection class

I am getting a 401 error when i try to hit the push URL. I am using HTTP BASIC authentication with "Application Key" as username and "Application Master Secret"as password. I am using JAVA HttpsUrlConnection class. I dont know whats wrong with my code.
` URL url = new URL("https://go.urbanairship.com/api/push");
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Content-Length", Integer.toString(data.length()));
String authString = "xxxxxxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyy";
authString = Base64Coder.encodeString(authString);
connection.setRequestProperty("Authorization","Basic "+ authString);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
int responseCode = connection.getResponseCode();
//Get the response
String responseLine = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine();`
Your authString should be composed of <application-key>:<application-master-secret>. Also your authstring may not be getting encoded properly. Try using Apache Commons Codec or ostermiller library to encode the authstring

Resources