I'm developing an app where HTML and javascript chunks are delivered down to different clients. I'm able to GET the html/javascript chunks by adding the following to web config file:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
</customHeaders>
</httpProtocol>
This is working great for doing GETS. The problem I'm running into is doing POSTs cross domain using jQuery:
$.ajax(
{
type: 'POST',
url: url,
crossDomain: true,
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(responseData, textStatus, jqXHR)
{
alert('Success');
},
error: function (responseData, textStatus, errorThrown)
{
alert('POST failed.');
}
});
I will have numerous clients consuming my app (hopefully). I thought about using a proxy, but I do not have control of the client servers so I'm not able to install a httpHandler to act as a proxy.
Any suggestions on how I can POST json data from different clients cross domain to my ASP.Net MVC app?
Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP.
The primary difference between ASP.NET MVC and ASP.NET Core is their cross-platform approach. ASP.NET Core can be used on Windows, Mac, or Linux, whereas ASP.NET MVC can only be used for applications on Windows.
I fiddled with my ajax call and it seems to be working (compare to the ajax call above):
$.ajax(
{
type: 'POST',
url: url,
crossDomain: true,
data: data,
dataType: 'json',
success: function(responseData, textStatus, jqXHR)
{
alert('success');
},
error: function (responseData, textStatus, errorThrown)
{
alert('POST failed.');
}
});
I removed "contentType: 'application/json'" and "JSON.stringify(...)" calls and I'm able to post to the server.
I'm not sure how to explain why it's working. Any ideas? Are there any security issues? I'm doing this all on my laptop. I set up 2 different websites via IIS 7. Will this make a difference?
Internally the JSONP response (the default type for cross-domain requests) is fetched by injecting a <script>
tag, which points to the URL. Because of that, only GET
method is possible with JSONP. Other methods will be ignored and fall back to GET
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With