CRM dynamics web api (400) Bad Request - asp.net-web-api

I have a crm dynamics plugin that makes a web api call but I am getting the following error:
The remote server returned an error: (400) Bad Request
I am using the following code
using (WebClient client = new WebClient())
{
string URI = "http://myserver/api/myaction";
string myParameters = string.Format("param1={0}", param1);
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
}
When I profile and debug this with the Plugin Registration tool the web api call returns a valid result and does not error.
Any ideas what is causing this infuriating issue?
UPDATE:
The plugin is running in sandbox mode and is on premise.
We have tried using async HttpClient but this requires the referencing of additional dlls which causes it own issues (adding the dlls to the GAC/ ILMerge) hence trying to get a working solution with WebClient initially which requires no additional dll referencing.

The issue turned out to be caused by an IIS binding issue.

Related

Youtube Data Api Search Endpoint 401 Error

I'm trying to use the Youtube search endpoint, which does not seem to require an OAuth token. I've read a few tutorials and they only pass an API key. I'm getting a "Failed to load resource: the server responded with a status of 401 ()" error in my console in Chrome Dev Tools. Specifically, looking at the Network tab I get this:
I notice it says that there is an error: "invalid_token" but I pass the api key so they must be talking about the OAuth token? I'm confused because it shouldn't need one, especially because I'm just doing a query for public data. Even the Try This API portion of the endpoint documentation does not need one. Most importantly, my call in Postman works and just pasting the endpoint in my browser directly works. Why doesn't it work? This is using an axios call from a ReactJS frontend.
const apiKey = 'MY_API_KEY';
const url = 'https://www.googleapis.com/youtube/v3/search';
const response = await axios.get(url, {
params: {
part: 'snippet',
maxResults: 5,
q: songName,
key: apiKey
}
});
What was happening was that I was using axios.defaults.headers.common['Authorization'] =Bearer ${params.access_token}; in other calls for another API. This causes default everything to have this access token! So what I did for now is delete axios.defaults.headers.common["Authorization"]; -- the solution is pretty obvious, just make sure you have no extra headers because Search is not a OAuth endpoint!

Passing Multiple Get Parameters to WebApi

I am working on a asp.net core 2.2 application. I want to pass two parameters(token and refresh token) to the asp.net core 2.2 web api to retrieve new token. When I am passing the values, i am getting an error
An unhandled exception occurred while processing the request.
AggregateException: One or more errors occurred. (Response status code does not indicate success: 404 (Not Found).)
System.Threading.Tasks.Task.Wait(int millisecondsTimeout, CancellationToken cancellationToken)
HttpRequestException: Response status code does not indicate success: 404 (Not Found).
Is this right way to pass multiple parameters and route it?
requestUrl is build as below:
string requestUrl = string.Format(Token_RefreshUserToken + "/{0}"+"/{1}", token,refreshToken);
requestUrl value is(web api controller name is 'Token'):
"Token/Refresh/eyJhbGciOiJIQrI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InJlZnJhbmNpc0BzdXlhdpdGkuY54tIiwiZXhwIojxNTYwMzMyOTk7hCJpc3MiOiJodHRwOi8vd3d3LnNlY3WeaXR5Lm9yZyIsImF1ZCI3rdh0dHA6Ly93d3cuc2VjdXJpdHkub3JnIn0.2Iw0VS_OgMjfpgt5V27mjCuLLqzlZBgRMpYgCTEHRP88E/IDwRYkf9idsVrBhBJJ5ymS+8RrZuSBSl+wywuKCs+Bw="
Client:
Task<TokenModel> userToken = _commonHelper.RecreateUserToken(tokenModel.TokenVal, tokenModel.RefreshToken);
userToken.Wait();
public async Task<TokenModel> RecreateUserToken(string token, string refreshToken)
{
string url = string.Format(WebApiConstants.Token_RefreshUserToken + "/{0}"+"/{1}", token,refreshToken);
var statusResponse = await _ApiHelper.GetAsync(url);
tokenData = await statusResponse.Content.ReadAsAsync<TokenModel>();
return tokenData;
}
Web Api method :
[HttpGet]
[Route("Refresh/{token}/{refreshToken}")]
public async Task<TokenValue> Refresh(string token, string refreshToken){ //logic }
It seems that request containing double escape sequence caused the problem.In development mode, try to run the web api project with Kestrel instead of IIS express.
ASP.NET Core application could be hosted on variety of web servers (IIS, Kestrel, Nginx, Apache, ...). All these web servers know nothing about request filtering (and particularly enabling of double escape) which is a native IIS feature. It's a hosting concern and ASP.NET Core application should not deal with it directly. If URL like http://youserver.com/Home/Phone/+12345 will reach ASP.NET Core pipeline, plus sign will not be treated in any special way and will get to string model as + character.
When you host your application on IIS, web.config is still in use, so you could configure <requestFiltering allowDoubleEscaping="true"/> as for usual ASP.NET application.
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="true" />
</security>
If you want to host application in another Web server, you should check how it handle special characters. Kestrel will just pass such URLs as is, so you don't need to take any specific actions if hosted on Kestrel.
Refer to here

Bulk Insert using C# with WEB API in Dynamics CRM

We are migrating our C# code from 2011 endpoint to Web API. We have API version 8.0. We have successfully implemented the Insert/Delete/Update operations using Web API but for bulk operations we are not getting how to implement this in C#. We referred https://gist.github.com/prabirshrestha/3929230 for implementations.
Here the code that we wrote:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "batch");
MultipartContent batchContent = new MultipartContent("batch");
request.Content = batchContent;
batchContent.Add(new HttpMessageContent(new
HttpRequestMessage(HttpMethod.Get, "contacts")));
response = httpClient.SendAsync(request);
response.Wait();
With this code we are getting error like saying:
This operation is not supported for a relative URI.
Please let us know if anybody can help us to implement this.
Also have question, like is bulk operations are part of Web API 8.0 version or there are introduced after this version?
According to this article, the v8 Web API supports batch operations.
It appears that the full URI of the Web API endpoint may be missing from your HTTPRequestMessage. It should be something like this:
[Organization URI]/api/data/v8.2/accounts
This question may also help.

Xamarin Salesforce SDK - The remote server returned an error: (400) Bad Request

I am using Xamarin Salesforce SDK Component v1.4.4.0.
Salesforce login and Authentication works fine.
But When I do SOQL Query Http error happening
var results = await Client.QueryAsync("SELECT Id, Name, AccountNumber, Phone, Website, Industry FROM Account");
The remote server returned an error: (400) Bad Request.
Above was the exception.Please help me out to find the issue.
Thanks in Advance!
Please check whether you are able to get the RestClient properly.

Is it possible to get value stored in session to Client App built using worklight?

I have stored value in session from worklight adapter by writing following piece of code :
var request = WL.Server.getClientRequest();
var session = request.getSession();
session.setAttribute("dataToExport", "Data To Return");
Is it possible to retrieve this value from client app using some worklight api or other way?
Instead of using WL.Server.getClientReuest, perhaps you can use WL.Client.addGlobalHeader in your client-side code.
WL.Client.addGlobalHeader
AddGlobalHeader(headerName, headerValue)
Adds an HTTP header to be used in server requests issued by
an IBM Worklight framework. The HTTP header is used in all requests
until removed by the WL.Client.removeGlobalHeader API call.
WL.Client.addGlobalHeader("MyCustomHeader","abcdefgh");

Resources