Why is the API call not working in ASP.NET Core 6 MVC, but the same API is working fine in ASP.NET MVC 5? - asp.net-core

One of my code is perfectly working in ASP.NET MVC 5, but when I am using almost same logic to call the API from ASP.NET Core 6 MVC, then the API always returns an error.
Same parameters and same address is being used in both technologies but the old approach is working.
Please see my old and new Logic to call this API, and guide me how to fix it.
The API Url is :
https://pcls1.craftyclicks.co.uk/json/rapidaddress?key=mykey&include_geocode=true&&postcode=DD68AB&response=data_formatted
ASP.NET MVC 5 - working fine:
using (var client = new HttpClient())
{
string addressUri = WebConfigurationManager.AppSettings["addressUri"];
var uri = addressUri + postcode.Replace(" ","") + "&response=data_formatted";
var response = await client.GetAsync(uri);
string textResult = await response.Content.ReadAsStringAsync();
lObjApiRes = JsonConvert.DeserializeObject<AddressLookupViewModel>(textResult);
}
ASP.NET Core 6 MVC - results in error:
using (HttpClient client = new HttpClient())
{
string addressUri = Configuration["CustomSettings:AddressUri"];
string uri = addressUri + postcode.Replace(" ", "") + "&response=data_formatted";
string textResult = "";
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = new Uri(uri),
Method = HttpMethod.Get,
};
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
textResult = await response.Content.ReadAsStringAsync();
}
}
The steps are simple to reproduce the case. Just create an ASP.NET Core 6 MVC project and try my code.
Please guide me to resolve the issue in a better way.
Why I am always getting this error:
{ "error_code":"0001",
"error_msg": "No data was found for the requested postcode." }

Related

In.net Framework 4.5 using RestSharp version 105.2.3 getting System.MissingMethodException when I try to use request.AddJsonBody() method

I am using RestSharp version 105.2.3 in .Net MVC framework 4.5 project to integrate external API, when I use request.AddJsonBody(obj) I get the runtime exception as System.MissingMethodException
Following are the code I used to call API
```
public string CheckCMSUser(RequestObjectModel requestObject)
{
RestClient client = new RestClient(requestObject.BaseURL + "CheckCMSUser");
RestRequest request = new RestRequest();
var payload = new RequestObjectCMSModel()
{
CompanyNumber = requestObject.CompanyNumber,
UserAccountEmail = requestObject.UserAccountEmail,
IncludeAllSubs = requestObject.IncludeAllSubs
};
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(payload);
request.AddHeader("WebAPI-Version", requestObject.WebAPIVersion);
request.AddHeader("Authorization", requestObject.Token);
var response = client.get(request);
return response.Content;
}
public void CheckCMSUser()
{
requestObj.CompanyNumber = "9999";
requestObj.UserAccountEmail = "user#example.com";
requestObj.IncludeAllSubs = "N";
requestObj.Token = _workContext.Token;
ValidUserResponseModel response = JsonConvert.DeserializeObject<ValidUserResponseModel>(_externalApiService.CheckCMSUser(requestObj));
}
```
Please help me to solve this
Thanks in Advance

Error in ASP.NET Core MVC and Web API project

I have an ASP.NET Core MVC and also Web API project.
This error occurs when I try to send project information to the API (of course API works fine and I do not think there is a problem):
UnsupportedMediaTypeException: No MediaTypeFormatter is available to read a "TokenModel" object of "text / plain" media content.
My code is:
public class TokenModel
{
public string Token { get; set; }
}
and in AuthController I have:
var _Client = _httpClientFactory.CreateClient("MyApiClient");
var jsonBody = JsonConvert.SerializeObject(login);
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = _Client.PostAsync("/Api/Authentication", content).Result;
if (response.IsSuccessStatusCode)
{
var token = response.Content.ReadAsAsync<TokenModel>().Result;
}
The error occurs on this line:
var token = response.Content.ReadAsAsync<TokenModel>().Result;
HomeController:
public IActionResult Index()
{
var token = User.FindFirst("AccessToken").Value;
return View(_user.GetAllUsers(token));
}
UserRepository:
public List<UserViewModel> GetAllUsers(string token)
{
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var res = _client.GetStringAsync(UrlMyApi).Result;
List<UserViewModel> users = JsonConvert.DeserializeObject<List<UserViewModel>>(res);
return users;
}
Your API is returning content-type of text/plain and none of the default media type formatters(MediaTypeFormatter) which ReadAsAsync<string>() will try to use support parsing it as is. They work with JSON/XML. You can go a couple of ways but maybe the easiest is to read the content as string and deserialize it after:
var tokenJSON = response.Content.ReadAsStringAsync().Result;
var token = JsonConvert.DeserializeObject<TokenModel>(tokenJSON);
Also, as you're using the Async methods, you should be returning Task from your actions and await the result instead of using .Result as you're just creating overhead currently.
var tokenJSON = await response.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<TokenModel>(tokenJSON);

IIS Express crashing asp.net 3.1 utf8 encoding

I used this function all the time in asp.net mvc to fetch data from an API but in asp.net core it's crashing out. I believe it may be an issue to do with the utf8 in .net core has anyone else had issues with this I just get an iis express error of -1 and the code bombs out
public async Task<List<Stock>> GetStockFromApi()
{
List<Stock> _result = new List<Stock>();
var uri = new Uri(string.Format(Constants.GetALlStock, string.Empty));
var response = await _httpClient.GetAsync(uri);
if (response.IsSuccessStatusCode) {
var byteArray = await response.Content.ReadAsByteArrayAsync();
var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
_result = JsonConvert.DeserializeObject<List<Stock>>(content);
}
return _result.ToList();
}
Make sure your api result (byteArray) in your case is correct.
It works well when I use your code in a brand new asp.net core 3.1 mvc project:
1.Add Microsoft.AspNetCore.Mvc.NewtonsoftJson package to project from PMC
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.0
2.Register it in startup.cs
services.AddControllersWithViews().AddNewtonsoftJson();
3. Test Action:
public async Task<List<Stock>> GetStockFromApi()
{
List<Stock> _result = new List<Stock>();
var uri = new Uri("https://localhost:44321/home/GetAllStock");
using (var client = new HttpClient())
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var byteArray = await response.Content.ReadAsByteArrayAsync();
var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
_result = JsonConvert.DeserializeObject<List<Stock>>(content);
}
return _result.ToList();
}
}
public ActionResult<List<Stock>> GetAllStock()
{
var list = new List<Stock>()
{
new Stock()
{
Id = 1,
Name="hello"
},
new Stock()
{
Id = 2,
Name="wrold"
},
};
return Ok(list);
}

PostAsync request with Array parameter on MVC Web API

I have Xamarin application that has POST request with array list of parameter and on my MVC WEB API we used code first Entity framework. Both was separated project solutions (.sln).
On my Xamarin project, I have PostAsync request which supplies List of array values.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
var data = JsonConvert.SerializeObject(parameters);
var content = new StringContent(data, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(url, content))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}
Then In my Web API controller I have same parameter with my client side also.
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpPost]
[Route("type={type}&param={param}")]
public BasicResponse applog([FromUri] ProfilingType type , List<string> param)
{
if (ModelState.IsValid == false)
{
throw new ModelValidationException("Model state is invalid.");
}
try
{
if(type == ProfilingType.Login)
{
var command = new SendDataProfilingCommand(param);
CommandHandler.Execute(command);
}
else
{
var command = new UpdateDataProfilingCommand(type,param);
CommandHandler.Execute(command);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return new BasicResponse
{
Status = true,
Message = Ok().ToString()
};
}
Since I'm not with the API, I want to test it first on Postman or even in the URL. but my problem was when i Try to test it using this url below
http://localhost:59828/api/users/applog?type=1&param=[1,Caloocan,Metro Manila,Philippines,0,0]
I received this message : No HTTP resource was found that matches the request URI ......
My Question is, How can I test my Web API with List Parameter on URL or in the Postman ? and What Format I can use when sending a post request into my Xamarin PostAsync request?
You don't need to send as Content.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
url = url + "?" + Parameter;
using (var response = await client.PostAsync(url))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}

How to consume REST service from a MVC 4 web application?

Can someone give me pointers on how to How to consume an external REST service from a MVC 4 web application? The services rely on an initial call with credentials base 64 encoded, then returns a token which is used for further web service queries.
I cannot find an easy primer on how to do this kind of thing, could someone help please?
I have all this working in classic ASP & JQuery but need to move over to an MVC 4 web application.
You could use the HttpClient class. Here's an example of how you could send a GET request and use Basic Authentication:
var client = new HttpClient();
client.BaseAddress = new Uri("http://foo.com");
var buffer = Encoding.ASCII.GetBytes("john:secret");
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
client.DefaultRequestHeaders.Authorization = authHeader;
var response = client.GetAsync("/api/authenticate").Result;
if (response.IsSuccessStatusCode)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
}
Once you have retrieved the access token you could make authenticated calls:
var client = new HttpClient();
client.BaseAddress = new Uri("http://foo.com");
string accessToken = ...
var authHeader = new AuthenticationHeaderValue("Bearar", accessToken);
client.DefaultRequestHeaders.Authorization = authHeader;
var response = client.GetAsync("/api/bar").Result;
if (response.IsSuccessStatusCode)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
}