url does not decode properly with request[] in C# - c#

I have an object like this:
public class adapterContext {
public HttpRequest Request;
}
adapterContext ac = new adapterContext();
ac.Response = context.Response;
I pass this object to my functions and use ac.Request[""] to get my url variables. However this somehow does not translate national/special characters correct. When I use f.ex this as part of the URL: prospectName=Tester+%e6+%f8+%e5
I get "Tester ? ? ?"
From the debugger I get: ac.Request["prospectName"][7] 65533 '�' char
Anyone have any idea how I should fix this?

there's a nice function, you should take care of: HttpUtility.UrlDecode(string, Encoding) ...
otherwise you need to adjust the globalization setting in your web.config (requestEncoding, responseEncoding ...)

Related

RestRequest Parameters adding logic

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'");

How to get the current url with route values?

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.

1. Forward slash in routing parameter

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

Get site url on mvc

I want to write a little helper function that returns the site url.
Coming from PHP and Codeigniter, I'm very upset that I can't get it to work the way I want.
Here's what I'm trying:
#{
var urlHelper = new UrlHelper(Html.ViewContext.RequestContext);
var baseurl = urlHelper.Content("~");
}
<script>
function base_url(url) {
url = url || "";
return '#baseurl' + url;
}
</script>
I want to return the base url of my application, so I can make ajax calls without worrying about paths. Here's how I intend to use it:
// Development
base_url(); // http://localhost:50024
// Production
base_url("Custom/Path"); // http://site.com/Custom/Path
How can I do something like that?
EDIT
I want absolute paths because I have abstracted js objects that makes my ajax calls.
So suppose I have:
function MyController() {
// ... js code
return $resource('../MyController/:id');
}
// then
var my_ctrl = MyController();
my_ctrl.id = 1;
my_ctrl.get(); // GET: ../MyController/1
This works when my route is http://localhost:8080/MyController/Edit but will fail when is http://localhost:8080/MyController .
I managed to do it like this:
#{
var url = Request.Url;
var baseurl = url.GetLeftPart(UriPartial.Authority);
}
Thank you all!
Are you aware of #Url.Action("actionname") and #Url.RouteUrl("routename") ?
Both of these should do what you're describing.
Instead of manually creating your URL's, you can use #Url.Action() to construct your URLs.
<p>#Url.Action("Index", "Home")</p>
/Home/Index
<p>#Url.Action("Edit", "Person", new { id = 1 })</p>
/Person/Edit/1
<p>#Url.Action("Search", "Book", new { title = "Gone With The Wind" })</p>
/Book/Search?title="Gone+With+The+Wind"
Now the absolute best reason to go with this option is that #Url.Action automatically applies any vanity URL routes you have defined in your Global.asax file. DRY as the sub-saharan desert! :)
In your case, your can create a 'custom path' in two ways.
Option A)
<p>#Url.Action("Path", "Custom")</p>
/Custom/Path
Option B)
You can create a route using the Global.asax file. So your controller/action combo can be anything you want, and you can create a custom vanity route url - regardless of the controller/action combo.

Input URL like http://example.com changes to http:/example.com in action input

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?:)/(?=[^/])", #"//");

Categories

Resources