ASP.Net MVC auto slugify Routes - c#

i have this code in my Controller:
string APIBaseurl = "https://sub.domain.de/";
[Route("VerseExkurs/Technologien/{technologie}")]
public async Task<ActionResult> Details(string technologie)
{
TechnologieRootobject TechnologieInfo = new TechnologieRootobject();
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(APIBaseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("items/technologien/" + technologie + "?access_token=token");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var TechnologieResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
TechnologieInfo = JsonConvert.DeserializeObject<TechnologieRootobject>(TechnologieResponse);
}
//returning the employee list to view
return View(TechnologieInfo.data);
}
}
But the Problem is, the "{technologie}" Variable is in some Cases with Spaces. Is there any way to automatically convert spaces in underdashes?

You have few options.
Utilize string.Replace() method
HttpResponseMessage Res = await client.GetAsync("items/technologien/" + technologie.Replace(" ", "_") + "?access_token=token");
Write a helper function that returns correct string
string removeSpaceFromString(string inputString)
{
return inputString.Replace(" ", "_"); // or some other method of doing that
}

Related

How can I implement getting Web API data in an ASP.NET MVC app using the repository architecture?

I have the following code which can retrieve data from an ASP.NET Web API:
string BaseUrl = "https://localhost:48262/";
public async Task<ActionResult> Index()
{
List<User> users= new List<User>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage res = await client.GetAsync("api/Users");
if (res.IsSuccessStatusCode)
{
var userdiagnosisRes = res.Content.ReadAsStringAsync().Result;
users = JsonConvert.DeserializeObject<List<User>>(userRes);
}
return View(users);
}
}
This code work, it's located in the controller and the data gets displayed on the Index page.
How can I implement this is a repository architecture? My app also has a DbContext connection with another database, but for this connection I have to retrieve data from a RESTapi. I want to be able to use the webapi data in other places than just this controller.
I take advantage of delegates and expressions:
public async Task<HttpResponseMessage> GetAsync(string url, Action<HttpRequestHeaders> headers, Action<IHttpRequestParameters> parameters)
{
using (var client = new HttpClient())
{
headers?.Invoke(client.DefaultRequestHeaders);
if (parameters != null)
{
parameters.Invoke(_httpRequestParameters);
var query = _httpRequestParameters.GetQueryString();
url += query;
}
return await client.GetAsync(url);
}
}
Then call it like this:
var test = await _handler.GetAsync("https://myurl.com", header =>
{
header.Add("mynewheader", "ha! it works!!");
header.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
header.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "fefe5648564grgrgr65446");
}, parameters =>
{
parameters.Add("test", "firstparam");
parameters.Add("test2", "secondparam");
});

PostAsync API giving Bad Gateway

I am invoking a third party POST API from my own API (again POST METHOD). The third party API is having a security key, and it is working fine on the POSTMAN tool. However, when I tries to invoke through code, I am getting error, 'Bad Gateway'. Following is the code which I tried.
public static async Task<string> GetDetailsfromThirdParty(string kszstrng)
{
string contentstring = string.Empty;
using (var client = new HttpClient())
{
string baseURL = "https://abcde.kz.in/b2/vhsearch-all";
string prms = kszstrng;// input parameters to API, in JSON Format- this is JSON String.
try
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("key", "value");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(prms);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await httpClient.PostAsync(baseURL, content).ConfigureAwait(false);
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
contentstring = result;
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
}
return contentstring;
}
}
I am getting error on this line:
var response = await httpClient.PostAsync(baseURL, content).ConfigureAwait(false);
While trying to execute I am getting the below error:
Not able to find out what's the issue? There is no network / Fireawall blockage. I have cross-verified with Systems Team as well.
Please suggest any issue with the code.
First of all, i recommend you to not declare the HttpClient in a using statement since this can cause a socket exhaustion (because the connections will stay open).
(see the docs for details)
Go for a static HttpClient (or use the IHttpClientFactory if you're project is .net Core).
I can't test your code since I'm not able to access this api.
But give it a try using a cleaner approach:
// static HttpClient
private static readonly HttpClient _HttpClient = new HttpClient();
// Can be used to set the baseUrl of the HttpClient from outside
public static void SetBaseUrl(Uri baseUrl)
{
_HttpClient.BaseAddress = baseUrl;
}
public static async Task<string> GetDetailsfromThirdParty(string kszstrng)
{
string contentstring = string.Empty;
string baseURL = "https://abcde.kz.in/b2/vhsearch-all";
string prms = kszstrng; // input parameters to API, in JSON Format- this is JSON String.
try
{
// Be aware of which headers you wanna clean if using the static HttpClient
_HttpClient.DefaultRequestHeaders.Accept.Clear();
_HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_HttpClient.DefaultRequestHeaders.Add("key", "value");
_HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
byte[] messageBytes = Encoding.UTF8.GetBytes(prms);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await _HttpClient.PostAsync(baseURL, content).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
contentstring = result;
}
}
catch (Exception ex)
{
// your exception handling
}
return contentstring;
}
Issue resolved. While forming the object to JSON String, there was an opening and closing angle brackets ([,]). Even though this is coming automatically while converting to JSON string, this was not accepted string at the vendor end. So I removed it and works perfectly. Thanks every one for the support.

How to call Post method with multiple parameter from C# project

I Have created a web api project , in values controller i created a method InsertHeading which takes three parameters and returns back a unique id. The method looks like this :-
public int InsertHeading([FromBody]string appid, [FromBody]string type, [FromBody]string detail)
{
int x = 1;
return 1;
}
I tried this variant as well
[HttpPost]
public int InsertHeading(string appid, string type, string detail)
{
int x = 1;
return 1;
}
This piece of code is running when i give url like :- http://server:port/LoggingAPi/Values/InsertHeading
from soap UI.
But when i try to call this method from my c# code i am getting 404 error how ever i try. Here are two ways i have tried :-
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://xxxxx:45422/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var append = new MasterLogInfo() { appid = "2", type = "request", detail = "test call from genesys" };
HttpResponseMessage response = await client.PostAsJsonAsync("LoggingAPI/Values/InsertMasterloginfo", append);
if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri finalURL = response.Headers.Location;
}
}
Method 2:-
// client.BaseAddress = new Uri("http://localhost:53117/");
client.BaseAddress = new Uri("http://xxxxxx:45422/");
client.DefaultRequestHeaders.Accept.Clear();
// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var user = new MasterLogInfo();
user.appid = "100";
user.typeRequest = "Test";
user.detail = "test call from genesys";
var response = client.PostAsync("LoggingAPI/Values/InsertMasterloginfo", new StringContent(new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;
// var response = client.PostAsync("Values/InsertHeading", new StringContent(new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;
if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri finalURL = response.Headers.Location;
}
}
If i use FromBody tag in parameters i get 500 internal server error, without it i get 404 error. Can anybody tell me what am i missing.I have removed the body of insert Heading for security purpose
Create an object that represents the payload coming in from the post. Then you can use it in the action parameters e.g. public int InsertHeading([FromBody] MyObject myObject)

Consuming a Web API in Xamarin

I've created a Web API in ASP.NET that is hosted on a web server. This Web API accesses a table in SQL Server where I have a table called Products with Id, ProductName, Description and Price, I did the tests via Postman and it is working correctly, but when I try to consume the method to bring a specific product via Xamarin application, I get the following error message in break mode:
System.Net.Http.HttpRequestException: Timeout exceeded getting exception details
public class DataService
{
public async Task<List<Product>> GetProductAsync(string ProductName)
{
using (var client = new HttpClient())
{
string url = "http://ProductsAPI.hostname.com/api";
try
{
var uri = url + "/" + ProductName.ToString();
HttpResponseMessage response = await client.GetAsync(uri);
var ProductJsonString = awaitresponse.Content.ReadAsStringAsync();
var Product = JsonConvert.DeserializeObject<List<Product>>(ProductJsonString);
return Product;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Here's what I've used in the past:
public string GetAPIJsonAsync(string URL)
{
using (WebClient wc = new WebClient())
{
return wc.DownloadString(URL);
}
}
This would return the raw JSON to whoever called it, and I would then convert it to the desirable object.
If you increase the timeout of the HttpClient, does it return more information?
Also, try Refit It does all the work for you, including deserializing into json.
This Works Perfectly for me
public static async Task<List<BranchMasterModel>> GetBranchList(int city)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(UrlAdd);//("http://192.168.101.119:8475/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "AuthToken"));
var result = await client.GetAsync("api/Master/V2/Branch/"+city);
string branch = await result.Content.ReadAsStringAsync();
var branches = JsonConvert.DeserializeObject<List<BranchMasterModel>>(branch);
return branches;
}

ASP.NET Call to API Endpoint returns 500 - Internal Server Error

I am calling a Rest API using a basic http authentication
public string Get(string LabName)
{
string userName = ConfigurationManager.AppSettings["username"];
string password = ConfigurationManager.AppSettings["password"];
string BaseURL = ConfigurationManager.AppSettings["BaseURL"];
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback( delegate { return true; });
Uri uri = new Uri(BaseURL);
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var byteArray = Encoding.ASCII.GetBytes(userName+":"+password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
string clarity_URL = BaseURL + "api/v2/labs?name=" + LabName;
var response = client.GetAsync(clarity_URL).Result;
string responseString = response.Content.ReadAsStringAsync().Result;
return responseString;
}
When I debug the code throws error on the line response like
Can anyone please suggest me what could be the issue.
A 500 Error usually means there is a problem with the API Server.
It would be a good idea to check the specific endpoint for any errors then check again with this code.
If you are checking against a web call that is working correctly, please ensure that the request method (GET / POST / PUT) is correctly aligned and the parameters match.

Categories