I'm using restsharp to perform a POST request to my endpoint.
When I add the body, I do this:
request.AddParameter("text/json", message, ParameterType.RequestBody);
The string message is done in this way: VALUE1.VALUE2
It is really simple.
But my endpoint receives only VALUE1
The endpoint signature is:
[HttpPost]
public HttpResponseMessage DoJob([FromBody] string id)
Do you know why? Do I have to encode somehow the message I'm sending?
Doing the same with postman for test purpose I'm not experiencing this behavior.
Thanks!
Here is my working example for RestSharp version 105.1.0.0:
var message = "VALUE1.VALUE2"
var client = new RestClient("http://localhost:64648"); //replace with your domain name
var request = new RestRequest("/Home/DoJob", Method.POST); //replace 'Home' with your controller name
request.RequestFormat = DataFormat.Json;
request.AddBody(new { id = message });
client.Execute(request);
And my endpoint definition
[HttpPost]
public HttpResponseMessage DoJob([System.Web.Http.FromBody] string id) {
//some code
}
Everything is working as expected.
BTW, if you want post array you need change only two places:
request.AddBody(new { ids = message.Split('.') });
And definition
[HttpPost]
public HttpResponseMessage DoJob([System.Web.Http.FromBody] string[] ids) {
//some code
}
I solved this problem passing the body in another way.
Instead of:
request.AddParameter("text/json", message, ParameterType.RequestBody);
I put:
request.RequestFormat = DataFormat.Json;
request.AddBody(message);
Now whatever character is inside the message, the message content (as long as it is json) is properly passed to my endpoint
Related
I am struggling to get this done and have tried various options but not able to post JSON when I read it from a file and pass it in request.AddJsonBody(jsonBody);
Note* It works, when i try passing it directly like: request.AddJsonBody(new { deviceId = "qa" });
But my requirement is to save request in a file and read it from there and pass it in request.AddJsonBody(jsonBody);
AddBody is deprecated, thus I am using AddJsonBody. Reading content from a file and then converting into JsonObject to pass in AddJsonBody doesn't work as it treats it like we have not passed valid json or treat it like an empty json.
[TestMethod]
public void createWithFile()
{
static readonly string textFile = #"C:\Users\RequestFiles\Users.txt"; // sample contents of my file : {"deviceId" : "qa"}
if (File.Exists(textFile))
{
text = File.ReadAllText(textFile);
}
JObject jsonBody = JObject.Parse(text);
Console.WriteLine(jsonBody);
RestClient client = new RestClient("myurl");
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(jsonBody);
request.AddHeader("Accept", "application/json");
var response = client.Execute(request);
Console.WriteLine(response.Content);
Console.WriteLine(response.StatusCode.ToString());
}
You can send any text as the request body. AddJsonBody specifically designed to serialise the object that is given as a parameter to JSON. If you have the JSON string already, just use the AddParameter with the RequestBody parameter type.
It is clear from the test code:
[Test]
public void Can_Be_Added_To_PUT_Request()
{
const Method httpMethod = Method.PUT;
var client = new RestClient(_server.Url);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);
const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
request.AddParameter(contentType, bodyData, ParameterType.RequestBody);
client.Execute(request);
AssertHasRequestBody(contentType, bodyData);
}
You need to set the correct content type, of course.
I have create gandi api code for create domain and for that i have write below code, but it show me 400 bad request error
public async System.Threading.Tasks.Task<JsonResult> InsertDomain(DomainDetails domainDetails)
{
HttpResponseMessage response = new HttpResponseMessage();
try
{
var url = "https://api.gandi.net/v5/domain/domains";
using ( var client = new HttpClient() )
{
var json = new JavaScriptSerializer().Serialize(domainDetails);
HttpContent HttpContent = new StringContent(json, Encoding.UTF8, "application/json");
var MyHttpClient = new HttpClient();
MyHttpClient.DefaultRequestHeaders.Add("authorization", GANDI_API_Key);
response = await MyHttpClient.PostAsync(url, HttpContent);
}
}
catch ( Exception ex )
{
throw;
}
return Json(new { result = response }, JsonRequestBehavior.AllowGet);
}
but when i try to pass same data using postman then it's working fine below code is my postman data
Body
{
"fqdn":"dedasdom1906.com",
"owner":
{
"city":"Paris",
"given":"Alice",
"family":"Doe",
"zip":"75001",
"country":"FR",
"streetaddr":"5 rue neuve",
"phone":"+33.123456789",
"state":"FR-J",
"type":"0",
"email":"alice#example.org"
}
}
Header
authorization : Apikey
Content-Type : application/json
I havent worked with this endpoint, but you are missing the return type.
the next thing i would try is to paste json string directly in the StringContent.
please paste the correct string content(rename the variable)
if none of this help you, please give more details.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
For the https://api.gandi.net/v5/domain/domains endpoint, use HTTP GET (HttpClient.GetAsync) to retrieve a list of your domains. Use HTTP POST (HttpClient.PostAsync) to create a new domain.
If you're trying to POST JSON, I would use the PostAsJsonAsync method, example here:
static async Task<Uri> CreateProductAsync(Product product)
{
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/products", product);
...
Also note your auth header needs to start with "apikey" though it looks like you have that working. Curl example:
curl -X GET \
https://api.gandi.net/v5/domain/domains \
-H 'authorization: Apikey your-api-key'
https://api.gandi.net/docs/domains/
I'm trying to consume data in my front-end which calls a API Broker and this API Broker calls my API. In my front-end I'm getting JSON data returned JSON with alot of backslashes in it. How can i prevent this? see code and errors below:
Consuming my API in my front-end:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string operation = "getClients";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(operation);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
My Api Broker gets the request and executes this:
As you can see the response content contains alot of backslashes.
This response is going back to my front-end where i receive the following content:
In this response there are even more backslashes added.
I hope someone recognizes this problem and knows a solution.
Thanks in advance!
I fixed it by serializing the string to a JSON object and than deserialize it .
I created WorkTableController.cs which is inherited from TableController (for using Offline Sync of Azure).
// PATCH tables/Work/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<Work> PatchWork(string id, Delta<Work> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/Work
public async Task<IHttpActionResult> PostWork(Work item)
{
WorkOrder current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
I also created AppServiceAccess.cs to invoke api from WorkTableController.cs
.....
client = new RestClient(appServiceUrl);
client.AddDefaultHeader("ZUMO-API-VERSION", "2.0.0");
client.Authenticator = new RestSharp.Authenticators.OAuth2AuthorizationRequestHeaderAuthenticator(result.AccessToken);
public static IRestResponse SendPostRequest(string url, object bodyParameter)
{
var request = new RestRequest(url, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(bodyParameter);
return client.Execute(request);
}
public static IRestResponse SendPatchRequest(string url, object bodyParameter)
{
var request = new RestRequest(url, Method.PATCH);
request.RequestFormat = DataFormat.Json;
request.AddBody(bodyParameter);
return client.Execute(request);
}
I can insert data to table Work in database by invoke SendPostRequest(), no problem. But I cannot update any record in table Work by invoke SendPatchRequest().
Could you give me a solution? Where is the problem in my code?
How to update a record in the table on Azure mobile backend by using TableController?
The update operation request would look like as follows:
PATCH https://{your-app-name}.azurewebsites.net/tables/{table-name}/{id}
Body: json payload
Based on your code, the code would look like as follows:
var client = new RestClient("https://{your-app-name}.azurewebsites.net");
client.AddDefaultHeader("ZUMO-API-VERSION", "2.0.0");
var request = new RestRequest("tables/Work/81c0ca73-e554-4166-a016-c80591bf5924", Method.PATCH);
request.RequestFormat = DataFormat.Json;
request.AddBody(new
{
text="hello world"
});
var result= client.Execute(request);
For your SendPatchRequest method, the parameter url need to look like this:
tables/{table-name}/{record-Id}
UPDATE:
You could set config.IncludeErrorDetailPolicy to IncludeErrorDetailPolicy.Always under Startup.MobileApp.cs of your mobile app back-end for retrieving detailed error messages to troubleshoot this issue. I just used postman to simulate the patch operation as follows:
I'm building an webapi in c# to be called by an outside server.
let's say my API address is www.server.com/webapi/service1
when I set the address above in the app that will use it, it sends a simple POST with an empty body to service1 and waits for a specific KEY as response (in body), like an authentication. ok.
the same service1 can be called, using POST too, passing a raw JSON in the body, and I'm using the [FromBody] attribute to get the body and process.
I tried this to manage the empty POST call and the call with body data:
[HttpPost]
[Route("webapi/service1")]
public HttpResponseMessage Post()
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(TokenKey.ToString(), System.Text.Encoding.UTF8, "text/html");
return resp;
}
[HttpPost]
[Route("webapi/service1")]
public async Task<HttpResponseMessage> Post([FromBody] RetornoChat retornoChat)
{
await closedChat(retornoChat); //process body
return resp;
}
but it was not working.I manage a workaround like the code below, I check if the class in [FromBody] is empty, if this is the case return the special string to validate and finish, if there is a body then get the data validate and process. I'm wondering if there is a better solution.
I really thought that the solution was to double the post method and when there was a body it would call the post with the [frombody] and when there is no body it would go to the empty post.
[HttpPost]
[Route("webapi/service1")]
public async Task<HttpResponseMessage> Post([FromBody] RetornoChat retornoChat)
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(TokenKey.ToString(), System.Text.Encoding.UTF8, "text/html");
if (retornoChat == null)
{
}
else
{
//get the body data and process
}
return resp;
}
Thanks in advance for your time!