I have a wcf service that exposes a rest endpoint. I want to test it using fiddler. I have a method like this :
[WebInvoke(Method = "POST", UriTemplate = "EditContact", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
string EditContact(string idContact, Contact Contact);
I input :
POST http://192.168.1.31/ContactLibrary2.0/Service.svc/rest/DeleteContact HTTP/1.1
User-Agent: Fiddler
Host: 192.168.1.31
Content-Type : application/json; Charset=UTF-8
{
"idContact":"67697",
"firstName":"6767",
"lastName":"afdgsg",
"email":"dfghdfdb",
"age":"120",
"street":"sdf",
"city":"dfghgfhjhdfgsdv",
"country":"sdfsd"
}
More code from my project you can see : HERE
I get http 400 error (bad request error). Ideas ?
Your request should look as shown below:
POST http://192.168.1.31/ContactLibrary2.0/Service.svc/rest/DeleteContact HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
{
"idContact":5,
"Contact":{
"idContact":"67697",
"firstName":"6767",
"lastName":"afdgsg",
"email":"dfghdfdb",
"age":"120",
"street":"sdf",
"city":"dfghgfhjhdfgsdv",
"country":"sdfsd"
}
}
Related
How can I name the piece of multipart/form-data given added to a request when I use the AddJsonBody() method?
I am attempting to get past the obsolete AddParameter() method.
Here's my code using the AddJsonBody() method:
request.AddJsonBody(Metadata);
There's an overload that allows me to specify the Content-Type, but I just need plain old application/json so I'm not using it. Here are the resulting relevant parts of my HTTP request as sent:
POST https://redacted/redacted HTTP/1.1
Content-Type: multipart/form-data; boundary=---------369C5A1F-30CF-450D-A5B4-2DBD93676056
-----------369C5A1F-30CF-450D-A5B4-2DBD93676056
Content-Type: application/json
Content-Disposition: form-data; name="application/json"
{"Date":"2021-07-28T14:27:01.0718841","FurtherInfo":"This is a metadata test."}
-----------369C5A1F-30CF-450D-A5B4-2DBD93676056
Content-Disposition: form-data; name="file"; filename="file20210728T1427010660244Z.txt"
Content-Type: text/plain
CL7~f`lz4ULMJa;]p-q!uH(-z*4iO'SHD)KYER5SI|e{3zW7^}J,%QPyD)$\K"
[...]
-----------369C5A1F-30CF-450D-A5B4-2DBD93676056--
As you can see, the "name" of the added parameter is application/json. I want it to be "metadata" instead. So I'm using this code to get things to be sent how I want, but this code is marked as obsolete:
Parameter metadata = new Parameter("metadata", JsonConvert.SerializeObject(Metadata), "application/json", ParameterType.RequestBody);
request.AddParameter(metadata);
Using this changes the HTTP request to:
POST https://redacted/redacted HTTP/1.1
Content-Type: multipart/form-data; boundary=---------8C24DE69-C111-418A-9C29-5D9DFABA320F
-----------8C24DE69-C111-418A-9C29-5D9DFABA320F
Content-Type: application/json
Content-Disposition: form-data; name="metadata"
{
"date": "2021-07-28T14:45:01.4650889",
"furtherInfo": "This is a metadata test."
}
-----------8C24DE69-C111-418A-9C29-5D9DFABA320F
Content-Disposition: form-data; name="file"; filename="file20210728T1445014611849Z.txt"
Content-Type: text/plain
zoRC)Z:c]\<#/z_q,k
[...]
-----------8C24DE69-C111-418A-9C29-5D9DFABA320F--
The specific serialization doesn't matter, only that it's valid JSON and has the name metadata.
Is there a way to use the newer AddJsonBody() method to do this? Is manipulating the parameter name on the roadmap?
as my understanding you are trying to send a file?
thi sis an example to send a file to API using RestSharp
using (WindowsIdentity.GetCurrent().Impersonate())
{
RestClient client = new RestClient(url);
var request = new RestRequest("/api/Upload", Method.POST, DataFormat.Json);
request.AddHeader("Cache-Control", "no-cache");
request.AlwaysMultipartFormData = true;
request.UseDefaultCredentials = true;
request.AddHeader("Content-Type", "multipart/form-data");
request.AddParameter("ServiceID", ServiceID, ParameterType.QueryString);
request.AddParameter("Description", description, ParameterType.QueryString);
//get byte[] , in reallife would be a stream
byte[] fileData = File.ReadAllBytes($#"C:\1\TEST\{filename}");
request.AddFileBytes("DocumentFile", fileData, filename, "multipart/form-data");
var result = client.Execute(request).Dump();
}
I found it!
From the class definition of RestRequest:
public IRestRequest AddParameter(string name, object value, string contentType, ParameterType type)
Instead of creating the Parameter, I can just add the parameter directly:
request.AddParameter("metadata", JsonConvert.SerializeObject(Metadata), "application/json", ParameterType.RequestBody);
And no more obsolete warning!
I have a VisualStudio17 serverless application project and am using .net core Web Api.
I want to confirm my SNS subscription, but I have a problem that AWS sends the POST request with header content-type set to text/plain; charset=UTF-8 while body is JSON.
Here's an example request from their documentation:
POST / HTTP/1.1
x-amz-sns-message-type: Notification
x-amz-sns-message-id: da41e39f-ea4d-435a-b922-c6aae3915ebe
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
x-amz-sns-subscription-arn: arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55
Content-Length: 761
Content-Type: text/plain; charset=UTF-8
Host: ec2-50-17-44-49.compute-1.amazonaws.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
{
"Type" : "Notification",
"MessageId" : "da41e39f-ea4d-435a-b922-c6aae3915ebe",
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Subject" : "test",
"Message" : "test message",
"Timestamp" : "2012-04-25T21:49:25.719Z",
"SignatureVersion" : "1",
"Signature" : "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=",
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",
"UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55"
}
Content-type: text, body JSON. This makes it parsing quite difficult, and a simple
public void Post([FromBody] string t) // or dynamic t for the matter
doesn't work and throws the Request was short circuited at action filter 'Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter'. exception.
Am I missing something? Why are they doing this and how do I work with this?
I made it work like I described in this answer, by adding text/plain to formats that JsonInputFormatter should format.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(config =>
{
foreach (var formatter in config.InputFormatters)
{
if (formatter.GetType() == typeof(JsonInputFormatter))
((JsonInputFormatter)formatter).SupportedMediaTypes.Add(
MediaTypeHeaderValue.Parse("text/plain"));
}
});
...
}
I have a wcf restful service that I need to get working in Chrome. I've read around and added all sorts of headers, etc but nothing is working. The POST works fine in IE, but when I get to Chrome, I get a 405 error on the OPTIONS request telling me that the method is not allowed. I've read where some people have added stuff to their global.asax file, but really don't feel like that should be necessary. I don't even have a global asax file and creating one just for the sole purpose of getting to work in chrome for development only seems crazy.
I'm using Aurelia's HTTP-Client library which uses just a simple XMLHttpRequest. Here's how it's configured:
this.Client = new HttpClient()
.configure(x => {
x.withBaseUrl("http://localhost/MyServices/MyService.svc/")
});
And I'm making the call like so:
this.Client.post("PostData/" + name,
{
version: 1
})
.then(resp => {
console.log(resp);
})
Here are the headers that I have added in my WCF Restful service WebConfig:
<add name="Access-Control-Allow-Origin" value="*" />
<!-- Not sure if these even do anything -->
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept, X-Requested-With" />
<add name="Access-Control-Allow-Methods" value="OPTIONS, GET, POST" />
Then in my service itself:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/PostData/{name}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
Data myData(byte id, string name);
Like I said above, it works fine in IE, but chrome gives me a preflight error. Here's a snippet of the fiddler response:
HTTP/1.1 405 Method Not Allowed
Entity
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Security
Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With
Access-Control-Allow-Methods: OPTIONS, GET, POST
Access-Control-Allow-Origin: *
Allow: POST
I also find that if I add x.withHeader("Content-Type", "application/json; charset=utf-8") to my Http-Client configuration, Chrome doesn't even do a GET request. It throws the error.
To sum it all up, I can do GET requests but not POST requests in Chrome. How do I fix it?
This problem has been bugging me all day, and I have spent a lot of time here, and on Google trying to find the right answer and trying lots of different fixes.
I have a Spring MVC Controller which is defined here:
#RequestMapping(value = "/searchAndCount", method = RequestMethod.GET, produces = "application/json", headers =
{ "Accept=application/json", "Content-Type=application/json" }, consumes = "application/json")
public #ResponseBody
RequestResults<?> searchAndCount(#RequestBody SearchInvoiceDTO searchInvoiceDto)
{
RequestResults<?> requestResults = invoiceApprovalService.searchAndCount(searchInvoiceDto);
return requestResults;
}
I know that with most gets, simple parameters can get sent back, but in this case, I found it better to put all my search criteria in one object and send that over. Which is why I am doing a #RequestBody.
Per previous fixes, I made sure that this has both headers that may be needed to accept JSON output.
The JSON String looks like:
String s1 = "{\"userId\":3, \"ddUserId\":301010651, \"customerCode\":\"QA\", \"customerId\":8}";
And yes, I have used the Jackson ObjectMapper tool verify this code will map correctly from this String to an Object, and vice-versa. When I look at the POJO, it does implement Serializable, and it does have a default constructor.
The Junit test works awesome and does return data:
MockHttpServletRequestBuilder requestBuilder =
MockMvcRequestBuilders.get("/invoices/searchAndCount").contentType(MediaType.APPLICATION_JSON)
.content(test);
this.mockMvc.perform(requestBuilder).andDo(print());
This does make the call to the Controller, I can see from the output what the headers are, and I can see that I actually get back real data which is great. So I feel there is not much more I can do from he controller side.
The real call to the controller comes from the SmartGWT RestDataSource.
The RequestMethod is defined in the datasource, here is the init method:
private InvoiceDataSource(String id)
{
setID(id);
setClientOnly(false);
// set up FETCH to use GET requests
OperationBinding fetch = new OperationBinding();
fetch.setOperationType(DSOperationType.FETCH);
fetch.setDataProtocol(DSProtocol.POSTMESSAGE);
fetch.setDataFormat(DSDataFormat.JSON);
DSRequest fetchProps = new DSRequest();
fetchProps.setHttpMethod("GET");
fetch.setRequestProperties(fetchProps);
// set up ADD to use POST requests
OperationBinding add = new OperationBinding();
add.setOperationType(DSOperationType.ADD);
add.setDataProtocol(DSProtocol.POSTMESSAGE);
// ===========================================
DSRequest addProps = new DSRequest();
addProps.setHttpMethod("POST");
add.setRequestProperties(addProps);
// set up UPDATE to use PUT
OperationBinding update = new OperationBinding();
update.setOperationType(DSOperationType.UPDATE);
update.setDataProtocol(DSProtocol.POSTMESSAGE);
// ===========================================
DSRequest updateProps = new DSRequest();
updateProps.setHttpMethod("PUT");
// updateProps.setContentType("application/json");
update.setRequestProperties(updateProps);
// set up REMOVE to use DELETE
OperationBinding remove = new OperationBinding();
remove.setOperationType(DSOperationType.REMOVE);
DSRequest removeProps = new DSRequest();
removeProps.setHttpMethod("DELETE");
remove.setRequestProperties(removeProps);
// apply all the operational bindings
setOperationBindings(fetch, add, update, remove);
init();
}
The Fetch is set to POSTMESSAGE which seems to be the best way to pass data using transformReponse.
#Override
protected Object transformRequest(DSRequest dsRequest)
{
// gets the correct URL - (web-app-root)/rest/invoices/searchAndCount
postProcessTransform(dsRequest);
System.out.println("InvoiceDataSource: transformRequest: START");
dsRequest.setContentType("application/json");
JavaScriptObject jso = dsRequest.getData();
// setting more headers, but this doesn't seem to change anything
dsRequest.setAttribute("Access-Control-Allow-Origin", "*");
dsRequest.setAttribute("Content-Type", "application/json");
dsRequest.setAttribute("Accept", "application/json");
String s1 = JSON.encode(jso);
System.out.println("InvoiceDataSource: transformRequest: FINISH: s1=" + s1);
return s1;
}
Since I know I have he correct URL, I also know I am spitting out that the variable "s1" also has the correct JSON data, and again I did test that JSON to make sure it would hit the controller correctly.
I also do have dependencies for Jackson as defined in the pom.xml file. I also have the message converters set in the springmvc-servlet.xml file. If these were not correct, the unit test would not work. However, if you need to see the pom.xml file or the springmvc-servlet.xml file, please let me know.
I have been researching and trying lots of things all day long now, and so far ... no luck.
I hope I have provided enough information, but if you need more, please let me know.
Ultimately, I hope I can tweak my SmartGWT RestDataSource to pass in the correct data to this controller to actually get data out of it.
UPDATE:
When I run this with Jetty in Eclipse, I am using Firefox 23.0.1 to open to my web-app.
Within the Console in Eclipse, here is what I can see:
[WARN] 415 - GET /rest/invoices/searchAndCount (127.0.0.1) 1440 bytes
Request headers
Host: 127.0.0.1:8888
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: GLog=%7B%0D%20%20%20%20left%3A22%2C%20%0D%20%20%20%20top%3A11%2C%20%0D%20%20%20%20width%3A705%2C%20%0D%20%20%20%20height%3A855%2C%20%0D%20%20%20%20priorityDefaults%3A%7B%0D%20%20%20%20%20%20%20%20Log%3A4%0D%20%20%20%20%7D%2C%20%0D%20%20%20%20defaultPriority%3A3%2C%20%0D%20%20%20%20trackRPC%3Atrue%0D%7D
Connection: keep-alive
If-Modified-Since: Thu, 01 Jan 1970 00:00:00 GMT
Response headers
Content-Type: text/html; charset=iso-8859-1
Content-Length: 1440
Accept: application/json
Notice that the Request header:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
does not show application/json
Also, the Request header: "Content-Type" is not present
When I use Chrome, the result is:
[WARN] 415 - GET /rest/invoices/searchAndCount (127.0.0.1) 1440 bytes
Request headers
Host: 127.0.0.1:8888
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36
DNT: 1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
If-Modified-Since: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: max-age=0
Response headers
Content-Type: text/html; charset=iso-8859-1
Content-Length: 1440
Accept: application/json
When I run from the JUnit test, there is always the "Content-Type:application/json" present. So, it seems that although I tell the SmartGWT RestDataSource that I am using JSON in several places ... the web-services call is not creating the right header.
UPDATE:
I added the following code to the SmartGWT RestDataSource transformRequest method:
Map<String, String> httpHeaders = new HashMap<String, String>();
httpHeaders.put("Accept", "*/*");
httpHeaders.put("Content-Type", "application/json");
dsRequest.setHttpHeaders(httpHeaders);
I can add the "Accept" Request-Header and I still got the 415 Unsupported Media error Message.
When I add the "Content-Type" Request-Header, then I get a 400 BAD REQUEST error message.
I get this in the console now:
[WARN] 400 - GET /rest/invoices/searchAndCount (127.0.0.1) 1418 bytes
Request headers
Host: 127.0.0.1:8888
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json
Response headers
Content-Type: text/html; charset=iso-8859-1
Content-Length: 1418
This took a lot of work, but I finally figured it out.
The verb GET doesn' work for my needs ... I am an idiot. No amount of work is going to make a GET work with sending my parameters as an object in the request data. So let me show the code that I had to change to make this work.
The SmartGWT RestDataSource, I changed;
fetchProps.setHttpMethod("GET"); to fetchProps.setHttpMethod("POST");
an I still kept: fetch.setDataProtocol(DSProtocol.POSTMESSAGE);
// set up FETCH to use GET requests
OperationBinding fetch = new OperationBinding();
fetch.setOperationType(DSOperationType.FETCH);
fetch.setDataProtocol(DSProtocol.POSTMESSAGE);
fetch.setDataFormat(DSDataFormat.JSON);
// ===========================================
DSRequest fetchProps = new DSRequest();
fetchProps.setHttpMethod("POST");
fetchProps.setContentType("application/json");
fetch.setRequestProperties(fetchProps);
Also in the same RestDataSource, in the "transformRequest" method, I added:
Map<String, String> httpHeaders = new HashMap<String, String>();
httpHeaders.put("Content-Type", "application/json");
httpHeaders.put("Accept", "application/json");
dsRequest.setHttpHeaders(httpHeaders);
This made sure that whatever browser I was using, these two headers are being manually set.
The Spring MVC Controller resides in the same web-app, so for now, this avoids any SOP cross-site domain issues until I can test that out. In the meantime, the header for my control looks like:
#RequestMapping(value = "/searchAndCount", method = RequestMethod.POST, headers =
{ "Accept=application/json", "Content-Type=application/json" })
public #ResponseBody
ArrayList<?> searchAndCountPOST(#RequestBody SearchInvoiceDTO searchInvoiceDto)
This work great to get called, and it returned my data. The original unit test I had was doing a MockMVc.get which worked and through me off. It must have recognized data coming through and changed the GET to a POST to make it work. My unit test was changed to a POST now, and that also works well.
I hope all this work pays off for someone else!
When I have this code
$.ajax({
type: 'POST',
//contentType: "application/json",
url: 'http://localhost:16329/Hello',
data: { name: 'norm' },
dataType: 'json'
});
in Fiddler I can see following raw request
POST http://localhost:16329/Hello HTTP/1.1
Host: localhost:16329
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:14693/WebSite1/index.html
Content-Length: 9
Origin: http://localhost:14693
Pragma: no-cache
Cache-Control: no-cache
name=norm
But what I'm trying is to set content-type from application/x-www-form-urlencoded to application/json. But this code
$.ajax({
type: "POST",
contentType: "application/json",
url: 'http://localhost:16329/Hello',
data: { name: 'norm' },
dataType: "json"
});
Generates strange request (which I can see in Fiddler)
OPTIONS http://localhost:16329/Hello HTTP/1.1
Host: localhost:16329
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: http://localhost:14693
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Pragma: no-cache
Cache-Control: no-cache
Why is that? What is OPTIONS when it should be POST there? And where is my content-type set to application/json? And request parameters has gone for some reason.
UPDATE 1
On server side I have really simple RESTful service.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestfulService : IRestfulService
{
[WebInvoke(
Method = "POST",
UriTemplate = "Hello",
ResponseFormat = WebMessageFormat.Json)]
public string HelloWorld(string name)
{
return "hello, " + name;
}
}
But for some reason I can't call this method with parameters.
UPDATE 2
Sorry for not answering so long.
I've added these headers to my server response
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST, GET, OPTIONS
It didn't help, I have Method not allowed error from server.
Here is what my fiddler says
So, now I can be sure that my server accepts POST, GET, OPTIONS (if response headers work like I expect). But why "Method not allowed"?
In WebView response from server (you can see Raw response on picture above) looks like this
It would seem that removing http:// from the URL option ensures the the correct HTTP POST header is sent.
I don't think you need to fully qualify the name of the host, just use a relative URL as below.
$.ajax({
type: "POST",
contentType: "application/json",
url: '/Hello',
data: { name: 'norm' },
dataType: "json"
});
An example of mine that works:
$.ajax({
type: "POST",
url: siteRoot + "api/SpaceGame/AddPlayer",
async: false,
data: JSON.stringify({ Name: playersShip.name, Credits: playersShip.credits }),
contentType: "application/json",
complete: function (data) {
console.log(data);
wait = false;
}
});
Possibly related:
jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox
After some more research I found out the OPTIONS header is used to find out if the request from the originating domain is allowed. Using fiddler, I added the following to the response headers from my server.
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST, GET, OPTIONS
Once the browser received this response it then sent off the correct POST request with JSON data. It would seem that the default form-urlencoded content type is considered safe and so does not undergo the extra cross domain checks.
It looks like you will need to add the previously mentioned headers to your servers response to the OPTIONS request. You should of course configure them to allow requests from specific domains rather then all.
I used the following jQuery to test this.
$.ajax({
type: "POST",
url: "http://myDomain.example/path/AddPlayer",
data: JSON.stringify({
Name: "Test",
Credits: 0
}),
//contentType: "application/json",
dataType: 'json',
complete: function(data) {
$("content").html(data);
}
});
References:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
http://enable-cors.org/
https://developer.mozilla.org/en/http_access_control
I can show you how I used it
function GetDenierValue() {
var denierid = $("#productDenierid").val() == '' ? 0 : $("#productDenierid").val();
var param = { 'productDenierid': denierid };
$.ajax({
url: "/Admin/ProductComposition/GetDenierValue",
dataType: "json",
contentType: "application/json;charset=utf-8",
type: "POST",
data: JSON.stringify(param),
success: function (msg) {
if (msg != null) {
return msg.URL;
}
}
});
}
So all you need to do for this to work is add:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
as a field to your post request and it'll work.
I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.
I'm using that construction:
$.ajax({
url: path,
type: "POST",
contentType: "text/plain",
data: {"some":"some"}
}
as you can see, if I use
contentType: "",
or
contentType: "text/plain", //chrome
Everything works fine.
I'm not 100% sure that it's all that you need, cause I've also changed headers.
If you use this:
contentType: "application/json"
AJAX won't sent GET or POST params to the server.... don't know why.
It took me hours to lear it today.
Just Use:
$.ajax(
{ url : 'http://blabla.example/wsGetReport.php',
data : myFormData, type : 'POST', dataType : 'json',
// contentType: "application/json",
success : function(wsQuery) { }
}
)
I found the solution for this problem here. Don't forget to allow verb OPTIONS on IIS app service handler.
Works fine. Thank you André Pedroso. :-)
I was fighting this same issue and it was caused by a lack of JSON.stringfy() i.e.
data: JSON.stringfy({ name: 'norm' }),
Hope this saves someone else a lot of time!
I had the same issue. I'm running a java rest app on a jboss server. But I think the solution is similar on an ASP .NET webapp.
Firefox makes a pre call to your server / rest url to check which options are allowed. That is the "OPTIONS" request which your server doesn't reply to accordingly. If this OPTIONS call is replied correct a second call is performed which is the actual "POST" request with json content.
This only happens when performing a cross-domain call. In your case calling 'http://localhost:16329/Hello' instead of calling a url path under the same domain '/Hello'
If you intend to make a cross domain call you have to enhance your rest service class with an annotated method the supports a "OPTIONS" http request. This is the according java implementation:
#Path("/rest")
public class RestfulService {
#POST
#Path("/Hello")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public string HelloWorld(string name)
{
return "hello, " + name;
}
//THIS NEEDS TO BE ADDED ADDITIONALLY IF MAKING CROSS-DOMAIN CALLS
#OPTIONS
#Path("/Hello")
#Produces(MediaType.TEXT_PLAIN+ ";charset=utf-8")
public Response checkOptions(){
return Response.status(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Methods", "POST, OPTIONS") //CAN BE ENHANCED WITH OTHER HTTP CALL METHODS
.build();
}
}
So I guess in .NET you have to add an additional method annotated with
[WebInvoke(
Method = "OPTIONS",
UriTemplate = "Hello",
ResponseFormat = WebMessageFormat.)]
where the following headers are set
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Methods", "POST, OPTIONS")
I got the solution to send the JSON data by POST request through jquery ajax. I used below code
var data = new Object();
data.p_clientId = 4;
data = JSON.stringify(data);
$.ajax({
method: "POST",
url: "http://192.168.1.141:8090/api/Client_Add",
data: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
I used 'Content-Type': 'text/plain' in header to send the raw json data.
Because if we use Content-Type: 'application/json' the request methods converted to OPTION, but using Content-Type: 'test/plain' the method does not get converted and remain as POST.
Hopefully this will help some one.
Hi These two lines worked for me.
contentType:"application/json; charset=utf-8",
dataType:"json"
$.ajax({
type: "POST",
url: "/v1/candidates",
data: obj,
**contentType:"application/json; charset=utf-8",
dataType:"json",**
success: function (data) {
table.row.add([
data.name, data.title
]).draw(false);
}
Thanks,
Prashant
In the jQuery.ajax documentation, contentType specifies the type of content to send to the server. The default value is "application/x-www-form-urlencoded; charset=UTF-8".
For cross-domain requests, if a content type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain is set, the OPTIONS method will be sent in the request header. It is a check that ajax does by the CORS policies to check if the methods that you request to the server (in this case POST) in your domain, are allowed
If the OPTIONS method on your server where the API is hosted is allowed, the request you made to the server initially is made, in this case the POST is sent.
If you are making the request to the same domain and same port, the OPTIONS method is not sent. If this is the case, one of the solutions is to use "http://localhost:<port>..." or just use relative paths where you are going to make the request.
But if the REST API in your backend is in another domain, so there are two solutions.
Do not put in ajax contentType: "application/json", and send the data either in JSON format as an Object or as a string, or a string with the parameters to send type key=value.
Enable CORS in your Rest API (that is, allow OPTIONS, POST methods, for any domain, or your domain where you make the request).
The problem is that in some cases it is necessary to set the type of content to send as "application/json", because the server where the API is hosted does not accept other types of content.
If you have control over the BackEnd and the REST API, I recommend enabling CORS on it. (Also applies if it is the same domain but different port).
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST, GET, OPTIONS
Or also allow other types of content like application/x-www-form-urlencoded or encode it in such a way that it also accepts strings with key=value parameters. This prevents jQuery from sending OPTIONS in its request header.
One last thing: if contentType: "application/json" is used and the server expects "application/json" as well, you should use JSON.stringify() on data, since when sending the request to the server, it seems to take the JSON as a string and not as an object. In my case, not using JSON.stringify() and using contentType: "application/json", returned me a server error with status 500