No custom/authorization Headers in MVC 5 controller - ajax

I have an MVC 5 ViewController which does not accept headers from an Ajax call. The ajax call origin is a different website then the controller.
The Ajax call looks like:
window.jQuery.ajax({
url: 'http://localhost:54155/TestView',
headers: {'Authorization': 'token'},
cache: false,
contentType: 'application/json; charset=utf-8',
method: 'Get',
dataType: 'json',
data: {}
}).success(alert('succes?'))
.error(alert('failed'))
});
Cors is enabled on the controller side:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
And I'm trying to reach this controller:
public class TestViewController : Controller
{
public ActionResult Index()
{
var keys = Request.Headers.AllKeys;
return View();
}
}
If I send the request to a WebApi based on a WEP API 2 controller, the headers are ok. If I send a request with postman to the mvc controller the headers are ok as well.
The Headers contain the header Access-Control-Request-Headers, which has the value authorization. But Request.Headers["Authorization"] is null.
Custom headers like X-MyHeader turn up as value from Access-Control-Request-Headers, but when used like a key, they are all null.
Which part am I missing?

I had a same kind of issue - but this might resolve your problem
Install Microsoft.AspNet.WebApi.Cors from NuGet - Run this command
(Install-Package Microsoft.AspNet.WebApi.Cors) in your package
manager console - this will install your Cors
Remove your access allow origin code from your Web.config file
If it is Web Api add the below cod in your WebApiConfig.cs if not try to add in your Gloabl.asax
var cors = new EnableCorsAttribute("*", "*", "*", "*");
config.EnableCors(cors);
You will be wondering where that method EnableCors() will come using System.Web.Http.Cors; add this line in your using and see the magic
This might solve your problem - Finally its not a good idea to access your MVC controller from different domain try you use WebApi
If you want to access your MVC controller try out your ajax code form the same domain
Because WebApi is stateless but MVC is kind of session - Thanks happy coding !!

Related

Error facing on communication between asp.net webapi server and angular2 application

I am facing the CORS related issue when i try to connect my angular2 application and asp.net webapi application.
Error:-
register:1 Access to XMLHttpRequest at 'http://localhost:49457/api/UserDetails' from origin 'http://localhost:4200' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4200, http://localhost:4200', but only one is allowed.
Here is my code for connecting for calling asp.net webapi url through my angular2 app:-
User.service.ts
GetUser(userobj:user):Observable<User>
{
return this.http.get<User>(`http://localhost:49457/api/UserDetails`,{responseType:"text"})
.subscribe(
function(response)
{
console.log("user details retreived successfully");
},
function(error)
{
console.log(error);
});
}
This is my code for asp.net webapi,
public class UserDetailsController : ApiController
{
private sampledbEntities dbentity = new sampledbEntities();
// GET api/<controller>
public IQueryable<Userdetail> GetUserdetails()
{
return dbentity.userdetails;
}
}
Actually when i run my asp.netwebapi server it is retrieving data correctly through browser.And also i have enabled
CORS in webapiconfig.cs,
void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
}
in web.config.cs,
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
After enabling CORS in Webapiconfig.cs and web.config also i am facing the same error.
Please clarify how do i come out of this error,
Replace http://localhost:4200 with "*" from EnableCorsAttribute method.
void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
}
and remove httpProtocol configuration settings from web.config.

Multiple CORS working for GET but not for PUT/POST with pre-flight requests Web api 2

When I configure CORS in my Web.config like following, every thing works:
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:3000"/>
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="accept, cache-control, credentials, content-type, authorization, origin, X-Requested-With, X-dev-mode"/>
</customHeaders>
However, when I try to enable multiple CORS like this:
// Filename: Global.asax.cs
protected override void Application_Start()
{
ApiConfig.Register(GlobalConfiguration.Configuration);
}
// Filename: ApiConfig.cs
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("http://localhost:3000,http://someOtherUrl.com/", "*", "*");
config.EnableCors(cors);
}
It works for GET (i.e. getting content, etc) but, when using POST/PUT (i.e. saving content, etc) it gives this error in browser (Chrome) console
Fetch API cannot load http://localhost:56214/api/1/content/SAVE. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The request is failing on OPTIONS. Please note that I do have custom handlers and my routes are also configured.
One more thing to mention is that the PUT/POST call to save content is an ajax call via react. Can that be an issue?
The problem is the trailing slash in your second URL. Change it to this and it works:
var cors = new EnableCorsAttribute("http://localhost:3000,http://someOtherUrl.com", "*", "*");
have you tried removing the blank space to the Access-Control-Allow-Methods like
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />

Ionic 3 http post request invalid HTTP status code 403 while jQuery ajax post is working perfectly

I am working on a mobile app. I need to fetch some data from WordPress website but the http request always through error Response for preflight has invalid HTTP status code 403
Typescript
this._http.post('http://www.example.com/wp-admin/admin-ajax.php',{
'action' : 'get_votes',
'postId' : 123456
})
.subscribe(data=>{
console.log(data);
},error=>{
console.log(error);
})
jQuery
The same thing is working in jQuery on local server
$.ajax({
url: 'http://www.example.com/wp-admin/admin-ajax.php',
type: 'post',
dataType: 'JSON',
data: {
'action': 'get_votes',
'postId': 123456
},
success: function(result) {
console.log(result);
},
error: function(error) {
console.log(error);
}
});
The cordova-plugin-whitelist is already installed.
config.xml
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
If you are testing with web browser, there you need to allow origin access for web browser. with chrome use plugin and configure it https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
If you are using with real device and it is still not working try to use header('Access-Control-Allow-Origin: *'); with your server side API file.
More Info here.
This is a CORS (cross-domain) issue. Your browser (not Angular) is sending an OPTIONS request before sending the actual POST request. Effectively, your server discards the OPTIONS request as not authenticated (or forbidden in your case). Please read this answer for more info.
Have you tried to set a 'content-type' header as 'application/x-www-form-urlencoded' or 'multipart/form-data'? I think is would result in the browser not to send an OPTIONS request before sending the POST request.
So, even if you solve the first problem (with the lack of OAuth header), you may still not be able to POST, because of the second problem.
You can also try and install the Chrome Allow-Control-Origin extension.
you can use ionic proxy to work arround the CORS problem,
ionic.config.json
"proxies": [
{
"path": "/api",
"proxyUrl": "http://www.example.com/wp-admin/admin-ajax.php"
}
]
and you call it this.http.post("/api")

Ajax POST to WCF Rest CORS-compliant WebService throws error 405

I'm doing some test over WCF REST WebServices and i'm stuck with the POST call.
I've created a webservice that exposes some test data about the good ol' Northwind DB and since i wish to consume it locally from a test HTML page and since i'd like to test CORS capabilities, i made it CORS compliant by following these instruction http://enable-cors.org/server_wcf.html.
Unfortunately problems comes out when i make POST calls.
Unlike GET calls (works very well), POST call throws this error:
What the hell is it? it seems that "Access-Control-Allow-Origin" header is not correctly managed client-side, beacuse in my EnableCrossOriginResourceSharingBehavior WCF class, the method "ApplyDispatchBehavior" (it filter "Access-Control-Allow-Origin" headers of the arrival requests) is hit when i make a POST call, but then Ajax call fails.
This is my jQuery Ajax post command:
//Create new object
var item = {
"CustomerId": "0",
"CompanyName": "prova"
};
//Push object
$.ajax({
type: "POST",
url: 'http://localhost:3434/NorthwindService.svc/Customer/Create',
crossDomain: true,
headers: {'Access-Control-Allow-Origin' : '*'},
data: JSON.stringify(item),
success: function (data) {
alert('ok!');
},
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
This is my WCF service Visual Studio 2013 project.
To test it, you only have to set "NorthwindConnectionString" in web.config to an existing one. The webservice method that i've problem with, is the POST to the "http://localhost:3434/NorthwindService.svc/Customer/Create" method, all the others works fine.
This is a preview of my method contract:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "Customer/Create", BodyStyle=WebMessageBodyStyle.WrappedRequest)]
void NewCustomer(CustomerDTO customer);
Thanks in advance.
I don't know what's going on, but thanks to supertopi and his link, i did the right steps to make it works. Unfortunately implementing all things discussed in here How to handle Ajax JQUERY POST request with WCF self-host did't works. I continued to get "405 Method not allowed" even by creating a new project.
The only thing that works in my case is the following:
1) Implement CustomHeaderMessageInspector and EnableCrossOriginResourceSharingBehavior classes and edit web.config as exposed in http://enable-cors.org/server_wcf.html.
2) Create in the service contract the following method:
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
3) Implementing it empty.
public void GetOptions()
{
}
It sounds crazy, but it actually works.
If i remove GetOptions() operation contract, i continue to get 405 error on my client. If i implement it like indicated by supertopi's link (obviously after remove all stuff created in the step 1), it doesn't work either.
Hope it helps.
Your HTTP Request Method is defined OPTIONS instead of POST.
That is why you get HTTP Response 405 Method not Allowed (no handler for OPTIONS request)
Change the type parameter in jQuery ajax constructor to "POST" and the request is routed to correct handler.

ExtJs 5 Ajax Request with ASP .NET

Despite my best efforts I am not able to send an Ajax request with Json data to a remote web server. I do not know what other places I can put enable CORS and am running out of ideas.
Azure Website App Settings:
cors:allowOrigins: *
MVC Controller: I had installed the NuGet Cors package
[EnableCors(origins: "*", headers: "*", methods: "*")]
Web.config:
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
ExtJs Ajax Request:
Ext.Ajax.request({
url: app.utilities.url,
defaultHeaders: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization,Content-Length, X-Requested-With'
},
cors: true,
useDefaultXhrHeader: false,
params: {
jsonData: Ext.util.JSON.encode(formData)
}
Yet I still get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at {my url} This can be fixed by moving the resource to the same domain or enabling CORS.
Is there something I am missing?
Would you consider JsonP (JSON with Padding)?
http://docs.sencha.com/extjs/6.0/6.0.0-classic/#!/api/Ext.data.JsonP
Only for the development purpose you can set below parameter in your browser.It works for me.
--disable-web-security --allow-file-access-from-files --allow-file-access

Resources