INTERNAL SERVER ERRRO IN ASP.NET MVC | Im using API Nodejs API
I'm getting this error :
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Access-Control-Allow-Origin: *
Connection: keep-alive
Keep-Alive: timeout=5
Date: Thu, 10 Jun 2021 10:43:08 GMT
ETag: W/"207-dot71BoPtBULXh2HngHqO05/OVY"
X-Powered-By: Express
Content-Length: 519
Content-Type: application/json; charset=utf-8
}}
[HttpPost]
public ActionResult Create(UserViewModel model)
{
try
{
string data = JsonConvert.SerializeObject(model);
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(client.BaseAddress + "users/registration", content).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View();
}
catch (Exception ex)
{
throw;
}
}
Related
I am trying to call a POST method of Moosend API from my MVC application. The Post call is working fine from Postman but throwing error from controller.
The Code goes as below:
public async Task<ActionResult> CreateEmailList()
{
try
{
using (var httpClient = new HttpClient { BaseAddress = new Uri(Baseurl) })
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
using (var content = new StringContent("{ \"Name\": \"APIList\"}", System.Text.Encoding.Default, "application/json"))
{
using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.json?apikey=0000", content))
{
string responseData = await response.Content.ReadAsStringAsync();
}
}
return View();
}
}
catch (Exception ex)
{
return View();
}
}
The Error I am getting is as below:
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-Robots-Tag: noindex, nofollow
X-Server-ID: 2
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, Accept, Cache-Control, X-Requested-With
Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE, PUT
Cache-Control: private
Date: Thu, 25 Nov 2021 06:58:44 GMT
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 5054
Content-Type: text/html; charset=utf-8
}}
Any suggestions on what am I missing here. Most of the POST example is similar to the code that I implemented.
I'm translating a javascript code that works to a C# (Xamarin application). And I getback from the server 400 'Bad Request'
I would like to know if the code I wrote in C# is correct or I missing something.
JS code:
function requestTokens(code) {
var codeVerifier = document.getElementById("codeVerifierValue").innerHTML;
var data = {
"grant_type": "authorization_code",
"client_id": "clientid",
"code": code,
"code_verifier": codeVerifier,
"redirect_uri": "https://redirectUrl"
};
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
},
url: "https://myUrl",
data: data,
success: responseFromPostRequest,
dataType: "json"
});
}
C# code:
private HttpClient _httpClient = new HttpClient();
private async Task<string> HttpPost(string url, DataDto data)
{
var jsonData = JsonConvert.SerializeObject(data);
var content = new StringContent(jsonData, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await _httpClient.PostAsync(new Uri(url), content);
}
Thanks for your help
Updated for log response:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: no-store
Connection: keep-alive
Date: Wed, 10 Nov 2021 17:37:43 GMT
Pragma: no-cache
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Android-Received-Millis: 1636565866035
X-Android-Response-Source: NETWORK 400
X-Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1636565857210
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Content-Length: 84
Content-Type: application/json
}}
So I found out that in the case of Content-type application/x-www-form-urlencoded it should not be a JSON file to be pasted in the post request.
There is the code sniped I found :
public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
using (var httpClient = new HttpClient())
{
using (var content = new FormUrlEncodedContent(postData))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsAsync<TResult>();
}
}
}
With this it works perfectly
I need to call an API from AppService by uri.
This is my API:
public ApiOutputBase Test_AddStudent(string name, int age, string address)
{
return new ApiOutputBase
{
Result = new Result { Status = true, Message = "OK,Test_AddStudent Done!" },
OuputValues = new List<object>() { name, age, address }
};
}
I use this Function to call it:
public async Task<bool> TestCallApi()
{
var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var testJson = "{\r\n \"name\": \"MyName\",\r\n \"age\": 25,\r\n \"address\": \"MyAddress\"\r\n}";
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));
// Call api success
if (response.IsSuccessStatusCode)
{
}
return true;
}
I used Swagger to call Test_AddStudent successfully. The testJson was copied from Swagger when I call Test_AddStudent successfully.
After that, I used Swagger to call TestCallApi without any error, but when I tried to debug the value of HttpResponseMessage, it showed this error:
{
StatusCode: 400,
ReasonPhrase: 'Bad Request',
Version: 1.1,
Content: System.Net.Http.StreamContent,
Headers: {
Pragma: no-cache
Cache-Control: no-store, no-cache
Date: Tue, 31 Oct 2017 02:12:45 GMT
Set-Cookie: Abp.Localization.CultureName=en; expires=Thu, 31-Oct-2019 02:12:45 GMT; path=/
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 405
Content-Type: application/json; charset=utf-8
Expires: -1
}
}
Have I missed something?
I finally found the root cause: I passed the wrong input to the api:
Wrong:
var testJson = "{\r\n \"name\": \"MyName\",\r\n \"age\": 25,\r\n \"address\": \"MyAddress\"\r\n}";
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));
Correct:
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent?name=MyName&age=25&address=MyAdress", "");
I am having a big problem when trying to authenticate to QuickBlox's server using a Token.
The method I use is:
public static async Task<LoginResponse> GetLoginResponseAsync(string email, string password)
{
LoginResponse result = null;
using (var client = new HttpClient())
{
string token = QbProvider.SessionResponse.Session.Token;
LoginRequest request = new LoginRequest()
{
Email = email,
Password = password
};
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, LoginUrlRequest))
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("QB-Token", token);
using (var response = await client.SendAsync(requestMessage))
{
string json = response.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<LoginResponse>(json);
}
}
}
return result;
}
The server's response is:
{"errors":["Token is required"]}
And the headers (debugging) in the client object are:
{
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Date: Thu, 01 Jun 2017 12:05:29 GMT
QuickBlox-REST-API-Version: 0.1.1
Server: openresty/1.9.15.1
Status: 401 Unauthorized
Strict-Transport-Security: max-age=31536000
WWW-Authenticate: OAuth realm=users
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 584a0dca-fc44-4114-9626-327ac1729f67
X-Runtime: 0.003430
X-XSS-Protection: 1; mode=block
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Content-Length: 32
}
}
When I use the Token in Postman, the server's response is successfull.
Do you know what am I doing wrong?
Thank you so much in advance!
Regards.
Try adding your token header using requestMessage.Headers.Add("QB-Token", token) instead of your Authorization one – by #dukedukes
I want to have a possibility to return complex response for requests in Web API. For example I want to return stream with some complex object.
I tried to do it with MultipartFormDataContent:
public static HttpResponseMessage GetMultipartResponse<T>(T responseData, Stream streamToReturn)
{
return new HttpResponseMessage
{
Content = new MultipartContent
{
new StreamContent(streamToReturn),
new ObjectContent<T>(responseData, new JsonMediaTypeFormatter())
}
};
}
I've got a normal HttpResponseMessage on server side. I can see by debugger how my Web API method returns this response, but on the client side I've got an error:
StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNccnVzdGFtX3NhbGFraHV0ZGlub3ZcZG9jdW1lbnRzXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xGaWxlU2VydmljZUFQSVxGaWxlU2VydmljZUFQSVxhcGlcZ2V0?=
Cache-Control: no-cache
Date: Tue, 26 Jul 2016 08:30:22 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 1444
Content-Type: application/json; charset=utf-8
Expires: -1
}
There is no other exceptions on client or server side and i can't get some more information with turn on error detail:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
UPDATE:
Try to read response on client side with:
var result = await response.Content.ReadAsMultipartAsync();
And got this exception:
Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'.
Where do I go wrong?
UPDATE 2:
I have normal response on the server side:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.MultipartContent, Headers:
{
Content-Type: multipart/multipart; boundary="3e6d3573-9031-41a7-b7f4-d1421bc1451d"
}
I found the error. I return my multipart content inside using:
using (var stream = MyFileStream())
{
var respone = MultipartResponseHelper.GetMultipartResponse(response, stream, Request);
return respone;
}
So it returns right response, but then stream inside multipartContent will disposed which is the reason of problem.