I am consuming a ASP.Net WEB API written in c# hosted in IIS6. When making a POST to the API it returns HTTP status 413. The API (not WCF) returns response as long as the content in the body is around 32+KB. If the size is like 40 KB then it errors out.
Below is the code snippet on the consumer side
string apiUrl = "https://a.com/api/emails/send";
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Accept", "application/json");
try
{
var jsonResponce = client.UploadString(apiUrl, jsonRequest);
var sendEmailResponce = JsonConvert.DeserializeObject<SendEmailResponce>(jsonResponce);
var emailMessageId = sendEmailResponce.EmailMessageId;
Console.WriteLine("email sent.");
}
catch (WebException exp)
{
var error = exp.ToString();
Console.WriteLine(error);
}
catch (Exception exp)
{
var error = exp.Message;
}
}
I am using IIS6 . Is there any setting in IIS / Code changes on the client might help me to get around this issue?
try this,
Launch “Internet Information Services (IIS) Manager”
Select the site that you are hosting your web application under it.
In the Features section, double click “Configuration Editor”
Under “Section” select: system.webServer then serverRuntime
Modify the “uploadReadAheadSize” section to be like 20MB (the value there is in Bytes)
Click Apply.
Related
I have a requirement where I am calling an API (programmatically PUT Method) from another API.
Both of the APIs are hosted as Azure Function App.
The request has nearly 600 rows.
The below method call is throwing the error: received an unexpected EOF or 0 bytes from the transport stream
If I send a request say 100-150 rows, it processes successfully.
I think that it is nothing to do with the code, it is related to the Azure Function app.
Please let me know if I need to add any configuration to the Azure Function app.
Thanks in Advance.
public async Task<List<CarPricing>> TestMethod(CarPricingModel request, string resourcePath,string token)
{
try
{
using var stream = StreamUtility.GenerateStreamFromString(JsonConvert.SerializeObject(request));
using var data= new StreamContent(stream);
data.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var queryParams = new Dictionary<string, string>()
{
{"id", "XXXXXXXXXXXXXXXXXXXXXX" }
};
var relativeUrl = QueryHelpers.AddQueryString(resourcePath, queryParams);
using var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Put,
Content = content,
RequestUri = new Uri(relativeUrl, UriKind.Relative)
};
var httpResponseMessage = await _httpClient.SendAsync(requestMessage);
httpStatusCode = httpResponseMessage.StatusCode;
var httpResponse = await httpResponseMessage.Content.ReadAsStreamAsync();
using var responseContent = new JsonTextReader(new StreamReader(httpResponse));
var response = new JsonSerializer().Deserialize<List<CarPricing>>(responseContent);
return response;
}
catch (Exception ex)
{
_log.LogError("API error {err_msg}",ex.Message);
throw;
}
}
Check the below steps that might help to fix the issue:
received an unexpected eof or 0 bytes from the transport stream
This error generally occurs during the HTTP Calls of .NET Core Applications.
TLS/SSL binding is supported in the Azure Function App. You can bind it through Azure Portal and using the Code.
If you’re using the HTTPS Protocol, apply this SSL Call before the request made as mentioned in the comments:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
or
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3| SecurityProtocolType.Tls| SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12
but the above error might come for many causes such as:
Client IP may be restricted, which you can add in Access Restrictions of the Function app API.
Typo Mistake or Incorrect URL of the API that is called programmatically from another Azure Function API.
Refer to this MS Doc for using the TLS/SSL Certificate Programmatically and SO Thread that shows how to use the TLS/SSL Certificate in Azure Function App.
I've created a ASP.Net Core 2.1 web application which gathers data from two sources. One is a SQL-database which supplies data via Entity Framework to my application. This one works fine. The other source is a REST API. I'm having troubles connecting to this.
I'm calling this Task which should return a user via his/hers e-mail address:
public async Task<PersonsModel> ReturnPersonByEmail(string email)
{
const string apiKey = "xxx";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://xx.xxx.xxxx.xx:xxx/xxxx/xxx/xx/xx/person/?email={email}");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("x-api-key", "123456");
var url = new Uri(client.BaseAddress.ToString());
string json = "";
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var response = await client.GetAsync(url);
using (var content = response.Content)
{
json = await content.ReadAsStringAsync();
}
}
catch (Exception e)
{
var exception = e;
}
return JsonConvert.DeserializeObject<PersonsModel>(json);
}
}
}
When I try calling it via Postman client.GetAsync(url) always returns an exception:
Message = "The remote certificate is invalid according to the validation procedure."
Message = "The SSL connection could not be established, see inner exception."
I tried adding the following codesegment to launchSettings.json(as per a reply to a similar question posted here: HttpClient client.GetAsync works in full .Net framework but not in .Net core 2.1? ) "DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER": "0" and then I get another error:
Message = "Error 12175 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'A security error has occurred'."
If you have any idea on what might cause this problem I would be very grateful for any help. Thanks!
I have tried to look for the solution for this with no success so far,
I am trying to call my ASP.NET WEB API (localhost:port) from Xamarin.Android (MainActivity).
I checked the API properly in Postman and it works as shown in the following screenshot
My code in Xamarin MainActivity is the following
try
{
using (var c = new HttpClient())
{
var client = new System.Net.Http.HttpClient();
var response = await client.GetAsync(new Uri("http://10.0.2.2:57348/api/remote"));
if (response.IsSuccessStatusCode)
{
Log.Info("myApp", "SUCCESS");
}
else
{
Log.Info("myApp", "ERROR: " + response.StatusCode.ToString());
}
}
}
catch (Exception X)
{
Log.Info("myApp", X.Message);
return X.Message;
}
I believe that 10.0.2.2 is to connect to the localhost from emulator -
When I run the code I get the error status as BadRequest
I also tried something like the following
try
{
Uri uri = new Uri("http://10.0.2.2:57348/api/remote");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
Log.Info("myApp", "Success");
}
}
}
catch (Exception X)
{
Log.Info("myApp", X.Message);
}
I get 400 Bad Request
400 Bad Request means I am doing something wrong as assuming that my code can connect to the API but the server is considering API Call as invalid?
Just in case if anyone wants to know the code in my API, its the following
public class remoteController : ApiController
{
// GET: api/remote
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Anyone has any idea about this, I have been trying different things for hours with no luck.
Also just to add, I tried 'http://10.0.2.2:57348/api/remote' in my Android Emulator's Chrome and I still get Bad Request response as shown in the following screenshot
but trying the same on my machine (browser) or Postman works fine using localhost
Please help
UPDATE:
Tried enabling External request on IIS Express using this http://www.lakshmikanth.com/enable-external-request-on-iis-express/
No luck,
The request is "bad" because the host header (in the request) is your 10.x.x.x. IP, and not localhost, which IIS Express won't accept.
We have an extension called "Conveyor", it's free and without configuration changes it opens up IIS Express to other machines on the network.
https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti#overview
I think it is because of cross origin error add this in startup.cs ( in configure method)
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
I have recently started working with web api's.
I need to download a file in C# project from a web api, which works fine when I hit the web api using postman's send and download option. Refer to the image, also please check the response in header's tab. This way, I am able to directly download the file to my computer.
I want to do the same from my C# project, I found following two links which shows how to download a file from web api.
https://code.msdn.microsoft.com/HttpClient-Downloading-to-4cc138fd
http://blogs.msdn.com/b/henrikn/archive/2012/02/16/downloading-a-google-map-to-local-file.aspx
I am using the following code in C# project to get the response:
private static async Task FileDownloadAsync()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "text/html");
try
{
// _address is exactly same which I use from postman
HttpResponseMessage response = await client.GetAsync(_address);
if (response.IsSuccessStatusCode)
{
}
else
{
}
}
catch (Exception)
{
throw;
}
}
}
However I am not getting the response at all (before I can start to convert the response to a file), please check the error message coming:
What am I missing here, any help would be appreciated.
As the (500s) error says - it's the Server that rejects the request. The only thing I see that could cause an issues is the charset encoding. Yours is the default UTF-8. You could try with other encodings.
Below method uses:
SSL certificate (comment out code for cert, if you don't use it)
Custom api header for additional layer of security (comment out Custom_Header_If_You_Need code, if you don't need that)
EnsureSuccessStatusCode will throw an error, when response is not 200. This error will be caught in and converted to a human readable string format to show on your screen (if you need to). Again, comment it out if you don't need that.
private byte[] DownloadMediaMethod(string mediaId)
{
var cert = new X509Certificate2("Keystore/p12_keystore.p12", "p12_keystore_password");
var handler = new WebRequestHandler { ClientCertificates = { cert } };
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Custom_Header_If_You_Need", "Value_For_Custom_Header");
var httpResponse = client.GetAsync(new Uri($"https://my_api.my_company.com/api/v1/my_media_controller/{mediaId}")).Result;
//Below one line is most relevant to this question, and will address your problem. Other code in this example if just to show the solution as a whole.
var result = httpResponse.Content.ReadAsByteArrayAsync().Result;
try
{
httpResponse.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
if (result == null || result.Length == 0) throw;
using (var ms = new MemoryStream(result))
{
var sr = new StreamReader(ms);
throw new Exception(sr.ReadToEnd(), ex);
}
}
return result;
}
}
Once you have your http response 200, you can use the received bytes[] as under to save them in a file:
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(content, 0, content.Length);
}
Your request header says that you accept HTML responses only. That could be a problem.
I am trying to send request to http://localhost/apptfg/get_biography_group?nombre_grupo=fondoflamenco which is a php based webservice that access to mysql database and retrieve information about the group but I always get a 404 not found when I execute the application in my windows phone 8 device, however when I debug the url in fiddler I get the right result which must be {"success":1,"group":[{"nombre_grupo":"fondoflamenco","anyo_creacion":"2006","descripcion":"Fondo Flamenco Flamenco is a group formed by three young Sevillian. Astola Alejandro Soto, Antonio Sanchez and Rafael Ruda M.R","musicos":"Rafael Ruda,Antonio Manuel Rios,"}]}
this is the HttpClient code I use in my application:
public async Task<string> makeHttpRequest(string group_name)
{
var resultstring = String.Empty;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "text/html");
try
{
resultstring = await client.GetStringAsync(new Uri("http://localhost/apptfg/get_group_biography.php?nombre_grupo=" + group_name));
client.Dispose();
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
return resultstring;
}