I am getting this error even though I added media formatter as follows. I am testing with postman. Postman headers content-type is application/json and body is x-www-form-urlencoded. How can I fix it?
"ExceptionMessage": "No MediaTypeFormatter is available to read an
object of type 'Initiate' from content with media type 'text/html'.",
"ExceptionType": "System.Net.Http.UnsupportedMediaTypeException"
Here is my code sample:
[RoutePrefix("api/v1/pin")]
public class GameController : ApiController
{
// POST: api/Game
[HttpPost, Route("initiation")]
public async System.Threading.Tasks.Task<Initiate> PurchaseInitiationAsync([FromBody]Initiate value)
{
if (value == null)
{
var message = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("Request is NULL! Please check your data.")),
ReasonPhrase = "Request is NULL! Please check your data."
};
throw new HttpResponseException(message);
}
HttpClient httpClient = new HttpClient();
HttpContent content = new StringContent(
JsonConvert.SerializeObject(value),
Encoding.UTF8,
"application/json"
);
HttpResponseMessage response =
await httpClient.PostAsync("http://test:1907/purchase_initiation", content);
var obj = response.Content.ReadAsAsync<Initiate>(
new List<MediaTypeFormatter>
{
new JsonMediaTypeFormatter()
}).Result;
return obj;
}
}
I can only reproduce this if the request content type hitting api/v1/pin/initiation is text/html. You say that your Postman settings are set to application/json and body is x-www-form-urlencoded, but from my testing if that was the case the exception you've shown above wouldn't be thrown.
I would double check that Postman is actually sending the correct content type header by opening the Postman console (CTRL+ALT+C) and inspecting the request headers.
Related
Service:
I have an endpoint that returns a custom "Error Details" json object when there is an error.
So for my Exception Middleware class I do something like this:
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var errorDetail = new ErrorDetail()
{
Title = "Some Title",
Detail = exception.Message
// some other fields
};
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var json = JsonSerializer.Serialize(errorDetail);
return context.Response.WriteAsync(json);
}
Client:
I consume the endpoint from a HttpClient in another service:
protected async Task<string> PostAsync(string path, string json)
{
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(path, UriKind.Relative));
var postContent = new StringContent(json, Encoding.UTF8, "application/json");
httpRequestMessage.Content = postContent;
var httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage);
// if error response I expect to get error details json, but instead get empty string:
var stringContent = await httpResponseMessage.Content.ReadAsStringAsync();
return stringContent;
}
For some reason httpResponseMessage.Content.ReadAsStringAsync() returns an empty string when trying to get the ErrorDetail json.
If I call the endpoint in Swagger, the errorDetail json is shown.
Strangely a different sort of error like 503 service unavailable and nginx returns error html, the .ReadAsStringAsync() will return the error html.
Why is httpResponseMessage.Content.ReadAsStringAsync() empty when there is an errorDetails json returned?
I'm using dotnet core 6 and aspnet core.
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 add a comment to an issue inside Fortify. When I POST what I think is the correct JSON, I receive the response "{"message":"Content was incorrectly formatted (expected application/json; charset=utf-8).","responseCode":400,"errorCode":-20209}"
However, if I use Fiddler to examine the message I'm POSTing and receiving the appropriate headers appear to be in place. What secondary issue could be causing this exception to be thrown?
Fortify v18.10.0187
.NET v4.6.2
Newtonsoft.Json v9.0.0
public static string PostCommentIssue(FortifyComment fc)
{
var content = JsonConvert.SerializeObject(fc);
var postUri = String.Format(Configuration.FortifyCommentsUri, fc.data.issueId);
return WebServiceHelper.PostMessage(postUri, content);
}
public static string PostMessage(string url, string content)
{
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
requestMessage.Headers.Add("Authorization", Configuration.FortifyAuthorization.ToHeader());
requestMessage.Content = new StringContent(content, Encoding.UTF8, JsonMediaTypeFormatter.DefaultMediaType.MediaType);
HttpResponseMessage hrm = HttpClient.SendAsync(requestMessage).Result;
hrm.EnsureSuccessStatusCode();
HttpContent hc = hrm.Content;
return hc.ReadAsStringAsync().Result;
}
FortifyComment is just an object with the basic elements of a comment in it. It's based on the Fortify response given on a query (thus the inner data element).
Using
FortifyComment fc = new FortifyComment();
fc.data.issueId = defect.id;
fc.data.comment = String.Format("TFS #{0}.", tfsNumber);
FortifyHelper.PostCommentIssue(fc);
I receive the 400 error. Screenshot of Fiddler intercept:
I'm writing a windows forms app where user have to enter email address and I need to check if it's valid.
I have found Mashape API but I get an exception;
"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Net.Http.dll" error in Unirest library.
Error occurs in line with msg.Headers.Add(header.Key, header.Value);
Values are:
header.Key = "Content-type"
header.Value = "application/json"
Debugger says:
"Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."
I can't find any solution, does anyone has any idea how to fix it?
Task<HttpResponse<EWSemail>> response = Unirest.post("https://email.p.mashape.com/")
.header("X-Mashape-Key", myKey)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.body("{\"email\":\"" + tbEmail.Text + "\"}")
.asJsonAsync<EWSemail>();
Unirest library:
private static Task<HttpResponseMessage> RequestHelper(HttpRequest request)
{
if (!request.Headers.ContainsKey("user-agent"))
{
request.Headers.Add("user-agent", USER_AGENT);
}
var client = new HttpClient();
var msg = new HttpRequestMessage(request.HttpMethod, request.URL);
foreach (var header in request.Headers)
{
msg.Headers.Add(header.Key, header.Value);
} // ^^"Content-Type" ^^ "application/json"
if (request.Body.Any())
{
msg.Content = request.Body;
}
return client.SendAsync(msg);
}
The error message says:
"Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."
Content-Type, as the name would imply, is a content header. Therefore, set it on msg.Content.Headers, not msg.Headers.
If I remember correctly, you can set it directly via msg.Content.Headers.ContentType = new MediaHeaderTypeValue("application/json");
OK, it doesn't work because syntax that Mashape provide is bad. In this case header.Key has to be "ContentType" (Reference: https://msdn.microsoft.com/en-us/library/system.net.httprequestheader%28v=vs.110%29.aspx).
I'm sorry for my rubbish post and thank you #codran, your answer helped me to find this answer.
I am trying to call Docusign REST API as is outlined in the "Step 3: Send signature request on behalf of User 2" Section in this link. I get the following error below. What is the boundary supposed set to? How do I correctly set it?
{
"errorCode": "INVALID_MULTI_PART_REQUEST",
"message": "An error was found while parsing the multipart request. Boundary terminator '--BOUNDARY; charset=utf-8--' was not found in the request."
}
public static string HttpRequest(string url, List<CELPHttpHeader> headerList, EnvelopeDefinition envelopeDefination)
{
string responseString = string.Empty;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("accept", "application/json");
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("multipart/form-data");
NameValueHeaderValue item = new NameValueHeaderValue("boundary", "BOUNDARY");
mediaType.Parameters.Add(item);
JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
HttpRequestMessage requestMessage = new HttpRequestMessage();
requestMessage.Method = HttpMethod.Post;
requestMessage.Content = new ObjectContent<EnvelopeDefinition>(envelopeDefination, formatter, mediaType);
foreach (CELPHttpHeader header in headerList)
{
client.DefaultRequestHeaders.Add(header.Name, header.Value);
}
try
{
Task<HttpResponseMessage> webTaskResult = client.PostAsync(url, requestMessage.Content);
webTaskResult.Wait();
HttpResponseMessage response = webTaskResult.Result;
}
catch (Exception ex)
{
}
return (responseString);
}
A snippet of what the API request should look like is below:
--BOUNDARY
Content-Type: application/json
Content-Disposition: form-data
{
<JSON request here>
}
--BOUNDARY
Content-Type: application/pdf
Content-Disposition: file; filename="test1.pdf"; documentid=1
Content-Transfer-Encoding: base64
JVBERi0xLjUNJeLjz9MNCjMwMDIgMCBvYmoNPDwvTGluZWFyaXplZCAxL0wgMTM1
<snipped>
V1sxIDMgMF0+PnN0cmVhbQ0KaN5iYhRZU8PEwCDsBCQY1wMJpicAAQYAHeIDMQ0K
ZW5kc3RyZWFtDWVuZG9iag1zdGFydHhyZWYNCjEzNjA0NjUNCiUlRU9GDQo=
--BOUNDARY--