Post Special Characters to web API from angular application - c#

API post method is as show below,
[HttpPost]
public HttpResponseMessage CreateTemplate([FromUri]string templateName)
{
//Code...
}
and Angular post method is as show below,
CreateTemplate(templateName: string): Observable<any> {
return this.httpClient.post<any>(Url + "Templates/CreateTemplate?templateName=" + templateName, "");
}
How can I send the special characters to web API? If I try to send special characters, I will end up with receiving null in Web API.

The # indicates a fragment, it and everything after it doesn't get sent to the server.
Given you use it as a query string parameter, you need to percent-encode it:
templateName=" + encudeURIcomponent(templateName)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Related

How to bind to a web api model when the request body includes escape characters?

I have an endpoint that looks like:
public IHttpActionResult SignUp([FromBody] AuthInput input)
Whenever the request body includes an escape character "\" the API fails to bind the data to the model. I have a guess that this is because the JSON would be considered "malformed."
I'd like to format the request body before the API attempts to bind it to the model and change all "\" to "\\"
Request body
{
"email": "mrsmith#usa.com",
"password": "badpassword\",
"firstName": "John",
"lastName": "Smith"
}
The backspace makes the input object "null"
Using c# ASP.NET 4.6.2
If you're generating the request body yourself:
Ideally you should be generating your Request Body JSON payload by serializing an existing DTO class.
If you can't do that, then you should safely escape string-values for use in directly-rendered JSON using .NET's built-in JavaScript string-escape utility methods:
In the .NET Framework Full Profile (so not .NET Core, .NET Standard, or .NET Framework Client Profile) you can use System.Web.HttpUtility.JavaScriptStringEncode.
Otherwise, use System.Text.Encodings.Web.JavaScriptEncoder.
If you're receiving bad input that you have no control over:
Approach 1: Work with the request-body directly:
This is the simplest approach, but requires you to do it for every controller action that receives malformed JSON:
public async Task<IHttpActionResult> SignUp()
{
String requestBody;
using( StreamReader rdr = new StreamReader( this.Request.Body ) )
{
requestBody = await rdr.ReadToEndAsync();
}
//
// Tweak the raw JSON text to make it parseable:
String requestBodyTweaked = requestBody.Replace( "\\\",", "\"," );
// Parse it and pass it on to the original `SignUp` method:
AuthInput dto = JsonConvert.DeserializeObject<AuthInput>( requestBodyTweaked );
return this.SignUp( dto );
}
// This is your current SignUp action method, it's unchanged except it's now `private`:
private IHttpActionResult SignUp( AuthInput input)
{
}
Approach 2: Middleware to intercept and modify all request bodies:
You could mitigate this using a middleware layer that intercepts the request body - but be very careful.
See this QA for instructions on how to intercept and modify an incoming request body: ASP NET Core modify/substitute a request body
I assume you'd want to edit the raw JSON text rather than parse it:

I am passing URL with & to my C# API Controller. However I only receive half of the URL upto & and anything after the & character is trimmed?

I am passing this web URL (http://localhost:4200/downloadDocuments/Ruzzy&Fuzzy.zip) to my download controller in Angular which further calls my API download controller.
My API controller looks something like this
[HttpGet]
[Route("GetDocumentFromFileStorage")]
public async Task<HttpResponseMessage> GetDocumentFromFileStorage(string documentName)
{
try
{
return await new TaskFactory().StartNew(
() =>
{
HttpResponseMessage response = _documentDownloadService.GetDocumentFromFileStorage(documentName.ToString());
return response;
});
}
catch (Exception ex)
{
Log4NetErrorLogger(ex);
return CreateHttpResponseMessage();
}
}
However the URL I receive in the controller is always http://localhost:4200/downloadDocuments/Ruzzy it trims everything after the & character causing the download to fail.
Please explain why this happens, I've tried to encode it with %26 and & but with no luck so far as it gives me an incomplete URL always.

C# .net Core web Api Get request # parameter

I use authorization via oauth.vk.com Docs here
When I call on web-browser
https://oauth.vk.com/authorize?client_id=1&display=page&redirect_uri=http://example.com/callback&scope=friends&response_type=token&v=5.80
After I sign in to vk.com and accept permissions to my server vk.com send Get request like this:
http://example.com/callback#access_token=c9186f0de67865740b9bd920a67320142434422007d16cf79031734fd450657cd4ba221106ce7232e74b7&expires_in=86400&user_id=1&email=example#mail.com
I don't know how to take #access_token in my Get method
Parameters with ? like expires_in, user_id and email I can take like this
[Route("vkauth")]
public class VKAuthController : Controller {
[HttpGet]
public string Get_VkAuth([FromQuery] string access_token, string expires_in, string user_id, string email) {
}
But how to take parameter #access_token?
Just use the HttpRequestMessage in the function and extract the token via the header (if the token is send using headers: Authorization)
For eg:
public string Get_VkAuth(HttpRequestMessage request,[FromQuery] string access_token, string expires_in, string user_id, string email) {
String access_token= request.Headers.Authorization.ToString();
}
correct Answer in comment by camilo-terevinto
Nothing after the # reaches the server. You are attempting to use a a
client-side implementation in server-side code. That's the first
signal you are not doing it correctly

ASP.NET Web Api - multiple params 500 error

' trying to make an web api controller with two parameters: one model object and string.
public string AddDevice(Device device, [FromBody] string userName)
{
// Some operations here
}
When I try it with one parameter on fiddler:
For Device object (body request):
{
"DeviceName":"name,
"StolenFlag":false
}
For string "[FromBody] string userName" (body request):
"userName"
It works fine. I just do not know how to make this method works with those two parameters. When I try connecting request body on fiddler like that:
{
"DeviceName":"name,
"StolenFlag":false
}
"userName"
I get an 500 error. It means, that server finds correct controller method but can't handle request. Any ideas?
First add the following line to WebApiConfig.cs in your App_Start folder.
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
It goes inside this function:
public static void Register(HttpConfiguration config)
Build your API and read the full error message from the Response. This should tell you exactly what's happening.
Since you can have only one parameter in the Request body you can change the method to accept username in the URI.
public string AddDevice([FromBody] Device device, string userName)
{
// Some operations here
return "";
}

Requesting "foreign" Api within ASP.NET Web Api

I write a Web Api 2 Project and within one Method (POSTing a new Location), I want to retrieve some Information, the user not provides (Country, City, region).
I found a solution in the Google Maps API:
http://maps.googleapis.com/maps/api/geocode/json?latlng=38.91845,1.44315&sensor=true
This meens, I must only provide the lat and lon coords within this URL.
How can I send this request and process the result within my own API Method?
My method is till now:
public string PostNewLocation(string mName, decimal mLat, decimal mLot)
{
// Here should be the calling and resolving of the Google API
// string mCity = ...
// string mCountry = ...
// Adding new location to database follows here and works fine...
}
public string PostNewLocation(string mName, decimal mLat, decimal mLot)
{
//do a get request to http://maps.googleapis.com/maps/api/geocode/json?latlng=38.91845,1.44315&sensor=true
//deserialize the json response to your own object and do stuff with it
var response = googleAPIService.Get(mLat, mLot);
//do something with the response
}

Categories

Resources