I have a GET end point which will take user name as parameter. Below is the action
[Route("user/{userName}")]
public User GetUserByName([FromUri] string userName)
{
// logic here
}
This is how i make the request.
var restClient = new RestClient("uri");
var request = new RestRequest("user/" + userName);
var response = restClient.Execute(request);
It worked fine for all cases till a user with name containing forward slash came.
Eg: Akbar/Badhusha
Then the request will looks like user/Akbar/Badhusha
This causing the request to return Not Fount error
I tried to add the parameter with AddQueryParameter method. All returning Not found error.
I also tried HttpUtility.UrlEncode
Also tried replacing / with %2f
Also tried user?userName=Akbar/Badhusha
All of them failed.
Is there any way to make it work?
Try removing [FromUri] from the parameter as shown below,
[Route("user")]
public User GetUserByName(string userName)
{
// logic here
}
And the request may look like,
user?userName=Akbar/Badhush
Related
I am having some issues finding information about adding some logic field in my RestRequest using V 107. I am trying to add a filter to my GET query
dl_document_indexed_date gt '2020-12-07T08:30:42.483Z'
There are a few other queries in the call which i am using Dictionary<string, string> to store them, and it works great however it only works if i am looking for something equal to, as adding it to the parameters it seems by default its equal to and i am not finding any way to add any other logic, gt/ge/lt/le etc. using the older version i would just append the url adding the logic i need, but i am not seeing a way to append the url either. Looking over their documentation i either missed it, cant find it, or its not there. Any help would be greatly appreciated! My method looks like this
public static async Task<string> GET_API(String RequestUrl, string RequestObject, Dictionary<string, string> parameters)
{
var request = new RestRequest(RequestObject);
var options = new RestClientOptions(RequestUrl)
{
ThrowOnAnyError = true,
Timeout = -1
};
var client = new RestClient(options);
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator("Bearer " + TokenManager.GetAccessTokenString("TRN"));
foreach (var parameter in parameters)
{
request.AddQueryParameter(parameter.Key, parameter.Value);
}
var response = await client.GetAsync(request);
return response.Content.ToString();
}
I send the BaseURL , the RequestObject would be table i am calling in the base URL, and my dictionary item contains the Field name, and the field values that i am dynamically generating on another method that would append the string. and example would be
parameters.Add("dl_document_name", "TableA");
which would append the URL with dl_document_name eq 'TableA'
it would call the API after i add the OAuth Token i create and return the data i need and send it back. or another option i guess could be appending the string with the logic i need to return the data
You should use OData, it's easy to implement and it has different kind of filters, you also can set which filters are usable and which aren't.
https://www.odata.org/
I figured out a work around, if i only have one i can add it to the first parameter and adding the filter as the first key, which will work unless i have multiple conditions that are not eq
parameters.Add("filter","dl_document_indexed_date gt '2020-12-07T08:30:42.483Z'");
I am connecting to a 3rd party API that requires calls to retrieve an authorization code and a token.
The API requires a redirect URL, which when returned, contains the authorization code attached to the query string.
So, on my side so I set up this controller below that will read the queryString.
Then, my app needs to fire a POST request to the API to get the token, and you will see me calling the controller the contains the POST request.
When I click my button to connect to the API, in my browser window, I do see that I am redirected to the GetGeologicalPeriod() controller below because I see the message:
you have reached the GeologicalPeriod endpoint.
And I do see the authorization code in the query string.
But I don't see anything else, no errors, nothing.
I was expecting to see the results retuned from the call to GetGeologicalPeriodToken, or at least an error that it failed, but I am getting nothing...not even in the browser console window.
So I am kind of at a loss as to what is actually happening.
Since this is on a development server, I can't step through it locally in Visual Studio.
Is there anyway to show messages or write to console so I can see what's going on?
Thanks!
[ApiController]
public class GeologicalPeriodController : ControllerBase
{
[HttpGet]
public ActionResult<String> GetGeologicalPeriod()
{
string getTest = "you have reached the GeologicalPeriod endpoint.";
var queryString = Request.Query["code"];
var postResult = GetGeologicalPeriodToken(queryString);
return postResult;
}
[HttpPost("AuthRequest")]
public ActionResult<String> GetGeologicalPeriodToken(string authCode)
{
string authToken = authCode;
string authString = "admin";
var queryString = Request.Query["code"];
var client = new RestClient("https://geologicalPeriod.geo.gov/oauth/token?accessType=professor&code=" + authCode + "&redirect_uri=https://jamaica.round.astro.edu/api/geologicalPeriodauth/geologicalPeriod/AuthRequest");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", authString);
IRestResponse response = client.Execute(request);
var apiResponse = response;
return apiResponse.Content.ToString();
}
I'm trying to retrieve the current request url with routes values, in order to have a return url with all needed values when reaching my controllers.
I tried HttpContext.Request.Path and HttpContext.Request.GetDisplayUrl() but it returns something like :
/Home/Products
What I actually need is to retrive the routes values to have :
/Home/Products?id=1
Is there a way to achieve that?
Thanks !
You can do this
HttpContext.Request.Path + HttpContext.Request.QueryString
Or for convenience you can create an extension method like this
public static string GetCurrentUrl(this HttpRequest httpRequest)
{
return httpRequest.Path + httpRequest.QueryString;
}
Then get current URL
var url = HttpContext.Request.GetCurrentUrl();
This link maybe helpful for you.
I've tried to logout from my session using GET request from IdentityServer4 docs.
HttpResponseMessage looks like this:
HttpResponseMessage res = await client.GetAsync($"connect/endsession?id_token_hint={idTokenHint}&post_logout_redirect_uri={postLogoutRedirectUri}");
At first, I have a problem with Uri lenght. When I send request, method catch exception
Invalid URI: The Uri scheme is too long.
To fix this problem I've tried send parameters into string like this:
var parameters = $"?id_token_hint={idTokenHint}&post_logout_redirect_uri={postLogoutRedirectUri}";
HttpResponseMessage res = await client.GetAsync("connect/endsession" + parameters );
Also add MaxRequestLineSize in Program.cs like this:
UseKestrel(options =>
{
options.Limits.MaxRequestLineSize = 20480;
})
Also tried this way: https://stackoverflow.com/a/32457474/9541386 But nothing working for me.
I've tried send this request by Postman. Request was sent
http://localhost:5000/connect/endsession?id_token_hint={idTokenHint}&post_logout_redirect_uri={postLogoutRedirectUri}
but in FindClientByIdAsync method from IClientStore interface clientId parameter looks like this:
But in normal case there is Id. I can't see what happens before it because it's first entry point.
How can I fix problem with Uri length and wrong parameter?
The problem is most likely an invalid character in the query parameters:
?id_token_hint={idTokenHint}&post_logout_redirect_uri={postLogoutRedirectUri}
In this case I suspect the string postLogoutRedirectUri that contains the character :, which is invalid if not escaped: %3A.
Encode the uri:
var encodedUri = System.Web.HttpUtility.UrlEncode(postLogoutRedirectUri);
And use this as parameter:
?id_token_hint={idTokenHint}&post_logout_redirect_uri={encodedUri}
While that may fix the problem, why don't you use the provided methods to signout? E.g.:
//using Microsoft.AspNetCore.Authentication;
//using Microsoft.AspNetCore.Mvc;
// Remove cookie
await HttpContext.SignOutAsync("Cookies");
// Signout oidc
await HttpContext.SignOutAsync("oidc");
I asked a question to get URL as action input here. Now I have a new problem. The passed URL to action changes from http://example.com to http:/example.com.
I want to know why and how can I resolve the problem.
P.S: I added this code to resolve but I think there may be another problems in future! the code is:
if ((url.Contains(":/")) && !(url.Contains("://")))
{
url = url.Replace(":/", "://");
}
The browser (or server) is replacing a double slash (illegal) with a single one.
Try it,
http://stackoverflow.com/questions/11853025//input-url-like-http-site-com-changes-to-http-site-com-in-action-input
(in Chrome) goes to:
http://stackoverflow.com/questions/11853025/input-url-like-http-site-com-changes-to-http-site-com-in-action-input
If I were you, I would remove the http:// from your path and add it later.
http://localhost:1619/Utility/PR/example.com/
Then, url = "http://" + url;
If you might get secure urls, add that to the route /http/example.com or /https/example.com
use regex:
string src = #"http://example.com";
string result = Regex.Replace(src, #"(?<=https?:/)/", "");
if you need to revert:
string src = #"http:/example.com";
string result = Regex.Replace(src, #"(?<=https?:)/(?=[^/])", #"//");