I already worked with web API and had a lot of problems like posting multiple parameters. I upgraded to WebApi2 to use routing attributes and now have problems like:
"message":"The requested resource does not support http method 'DELETE'."
I spent all day searching Stack Overflow and the web to solve the problem:
Removed webdav
In http protocol allow all get,put,post,delete
Added the [HTTPDelete] attribute
Added name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"
Searched Google for the necessary help here
Can someone please guide me on this?
I had the same problem. Adding the below code to your web.config should fix the problem under the system.webserver section:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
I had the same problem, because my controller was like this:
[HttpDelete]
public HttpResponseMessage Delete(string Id)
{
....
}
And on the client I used the send the ID as request body:
var url = '/api/upload';
var data = JSON.stringify({ 'Id': id }); // <-- In the body
$.ajax({
url: url,
type: 'DELETE',
data: data, // <-- in the body
contentType: 'application/json'
})
When I changed the client to use it as URL parameter instead it worked:
var url = '/api/upload/' + id; // <- In the URL
$.ajax({
url: url,
type: 'DELETE',
contentType: 'application/json'
});
The JavaScript code for the DELETE verb must be like this:
$.ajax({
**url: "/api/SomeController/" + id,**
type: "DELETE",
dataType: "json",
success: function(data, statusText) {
alert(data);
},
error: function(request, textStatus, error) {
alert(error);
debugger;
}
});
Do NOT use something like this,
...
data: {id:id}
...
as when you are using the POST method.
Related
Am trying pull data from .net core web api using ajax call am getting the below error
Failed to load http://localhost:8085/api/menu: Response for preflight has invalid HTTP status code 404.
but am getting data sucessfully from postman.
am trying below code for ajax
$(document).ready(function(){
$.ajax({
url: 'http:/localhost:8085/api/menu',
type: 'GET',
dataType: 'json',
data: '{ }',
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
}
});
});
I have added below tag in web.config file
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please suggest your thoughts.
Thanx in advance.
you can define your policy in Startup file as a part of ConfigureServices method
for example:
{
services.AddCors(c => {
c.AddPolicy("policyName", p => {
p.AllowAnyOrigin().AllowAnyMethod();
});
});
}
and then in Configure method
app.UseCors("policyName");
$.ajax({
url: path,
type: "POST",
data: parameters,
success: function (response) {
...
},
error: function (xhr, textStatus, err) {
...
// xhr.responseJSON is undefined here even tho the locally it would
}
});
After wasting some time , figured out the prob. Include below section in web config and voila.
This also works for Azure.
<system.webServer>
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
the ajax call was working fine locally I just needed to add this to the web config:
<system.webServer>
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
I need to allow a custom header called "secretToken". And every call to my webapi, the user should pass this header.
I searched for a way to do that, but I could not found an easy way. How can I allow this custom header?
There's one more thing in .config file:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,auth-key" />
</customHeaders>
</httpProtocol>
You mentioned 'allow' means passing from client? Which client?
If JavaScript, you can do something like this.
$.ajax({
type: 'GET',
url: '/api/values',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: { 'X-My-Secret-Token': 'Token' },
success: function (data) {
}
});
If .NET client, you can do something like this.
string url = "http://www.myurl/api/values";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-My-Secret-Token", "Token");
var message = client.GetAsync(url).Result;
In Web API, you can read the header in HttpRequestMessage object from any component in the pipeline. For example, you can read the header from a handler like this.
public class MyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var headers = request.Headers;
if (headers.Contains("X-My-Secret-Token"))
{
string token = headers.GetValues("X-My-Secret-Token").First();
}
}
}
I have a WCF Service which returns a string. I am trying to call it using a cross domain JsonP request. This is working in IE but no other browser. I get a parser error back in Firefox and Chrome.
From reading through various articles i seem to think that maybe the service needs to be returning the result back as a different format. Any ideas would be helpful, here is my code.
WCF Service Code
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string SponsorLayout2(string projectScope, int projectYear, int imageHeight)
{
// Mock data
projectScope = "uk";
projectYear = 2012;
imageHeight = 42;
// Get projectId
var project = Projects.GetProjectByProjectScopeAndYear(projectScope, projectYear);
// Get project sponsor layouts
var projectSponsorLayout = ProjectSponsorLayouts.GetProjectSponsorLayout(project.Id, imageHeight);
// Return the sponsors
if (projectSponsorLayout != null)
return projectSponsorLayout.Body;
return null;
}
Jquery Ajax Call
$.ajax({
cache: false,
type: "GET",
async: false,
data: {},
url: "http://127.0.0.1:8082/HtmlService.svc/SponsorLayout2",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
alert("success");
},
error: function (xhr) {
alert("error");
alert(xhr.statusText);
},
complete: function(jqXHR, textStatus) {
alert(textStatus);
}
});
I found out why I was getting the problem stated above and thought I would share this with you.
For some reason there was a conflict between this attribute
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
which sits on top of my class
public class MyClass
and this rule in my web.config file
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
I have ended up commenting the rule out in my web.config and everything come to life. Because my service is an AJAX ready service, the attribute is added above the class out of the box. Anyway this worked for me and hope it helps anyone else in the same situation.
I have a page with several user controls that use Ajax. When I try to do a response.redirect from this page, Ajax traps the call and does not allow the redirect.
How can I do a response.redirect from an Ajax page?
Thanks...
How much control over the AJAX actions do you have in the user controls? If you can modify the client side, the easiest thing to do is to return a JSON object that you can parse and send the URL that you want to redirect to as data. Once you get the data on the client, simply set window.location.href to the url.
With jQuery it would look something like:
$.ajax({
url: '/some/url',
dataType: 'json',
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data.Redirect) {
window.location.href = data.Redirect;
}
else {
...handle other responses...
}
}
... more options...
});
as I stated in the other question:
add this to your web.config
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>