Enable cors in wcf - ajax - c#

I am a beginner in WCF, I have been attempting to enable CORS for a WCF service hosted in my IIS. I have gone through several posts and Stack Overflow questions, and all answers are leading me to different solutions and none of them works.
Can someone explain me how to achive this? I tried creating a global.asax and adding begin_request event to set up the headers, but it changed nothing.
This is what I used:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
Where should I start for this and which is the best way for achieving this?

I assume WCF service is up and running.Fix in Web.config .Add below section in system.webServer section.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
Caution
NOTE! The Access-Control-Allow-Origin setting is set to a value of "*". This will allow all callers to have access. You can specify only your caller.
From your existing implementation it should work.However I have slightly tweaked the code and it works for me.
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization, Origin, Content-Type, Accept, X-Requested-With");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}

Related

CORS blocked access even though the local address is allowed in server side

I have an Angular page which is making use of an Entity Framework powered ASP.NET server. Both Angular and ASP.NET applications run on different local addresses. To prevent CORS errors, I have configured some settings at the server side.
At the ASP.NET side, in WebApiConfig.cs I have enabled all of the access permissions from the Angular local address with this;
config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "*", methods: "*"));
However, when I trying to Edit a value from the Angular page, I am still having the CORS error.
Access to XMLHttpRequest at 'http://localhost:62677/Assets/Edit/177738ba-16cd-4b08-b339-974f0547e626' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Inserting a new value to the database or getting all of the values from the database is working without the CORS error but editing an existing value gives an error.
I tried to add a break-point at the above code in WebApiConfig.cs and debug it, however, line of code is never reached.
Any help is appreciated, thanks
Addition: Also I have the following configurations in my Web.config file;
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
New ERROR after implementing Shyam Vemula's solution:
Access to XMLHttpRequest at 'http://localhost:62677/Assets/Edit/177738ba-16cd-4b08-b339-974f0547e626' from origin 'http://localhost:4200' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
Try this one. Add the following in Global.asmx
void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var response = context.Response;
// enable CORS
response.AddHeader("Access-Control-Allow-Origin", "*");
if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.End();
}
}
and Remove this from Web.config file
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />

Enable Http Options Preflight Request For ASP.NET Web Forms ApiController

I have an ASP.NET web form application with a couple of API controllers.
One of my controllers gets a request from a different domain. Since this request contains an Authorization header the browser sends a preflight request (HTTP OPTIONS).
At first, I tried to add the following in the web config :
<httpProtocol>
<customHeaders>
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE"/>
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type"/>
<remove name="X-Powered-By"/>
</customHeaders>
</httpProtocol>
But it didn't work, and the browser failed with "405 - method not allowed" error.
Only when adding the following code to global.asax I successfully received the preflight request
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Allow‌-Credentials", "true");
HttpContext.Current.Response.End();
}
}
The thing that bothers me is that this code enables preflight request for all web API controllers, and I want to enable it only for one of my controllers.
I know I can solve it using a function with [HttpOptions] annotation, but I don't want to add it for each function in the controller. Is there a way to enable it for all controller functions?
Add this method to the Global.asax.cs and put this code
using System.Web;
namespace Example
{
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}
}
Nice Blog For you

401.2 response when call WEB API from MVC project

I am running a WEB API project locally through Visual studio, on port 49374.
I am then running an MVC project locally through VS, on port 57062.
I am trying to call an API in my WEB API project (49374), from the MVC project(57062), but am getting a 401.2 response, see below:
When I call the API directly from the browser, it works fine.
CORS is setup in the Web API Web config as follows:
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:57062" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
<add name="Access-Control-Allow-Credentials" value="true" />
<!--<add name="Access-Control-Allow-Credential-Header" value="true"/>-->
</customHeaders>
</httpProtocol>
and the project has the following settings on VS:
I am out of ideas as to what the problem could be - can anyone suggest anything?
I have encountered the same probleme. IIS Express does not seem to use the custom headers in the web.config.
I fixed it by adding in the global.asax.cs :
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Context.Request.Headers.AllKeys.Contains("Origin"))
{
Context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:57062");
Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
if (Context.Request.HttpMethod == "OPTIONS") Context.Response.End();
}
}

HTTP Authorization header not working

I have the following angular code in which I had set the access_token also.
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
import { HttpHeaders } from '#angular/common/http';
import { Headers, Response } from '#angular/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
// tslint:disable-next-line:max-line-length
'Authorization': 'bearer zhGMjEFn5SlPYPB4opK57CiPP02MuR-lk10rvYsGU0PcQUyo5U6JHaH5NgdmDpNHSfrkuDLZYIr3xAio_aG0WZbKWM28dgP9BN2i-ERS8PQ97_oXP93AVzHj60RivH5EsfImmEb3mPSSEw68lafAQHe4kQyEptkxTtYlfPczrdQR4hWVOkvA_Hk8JuxFQpUmj0ReRhP5xXfoJcsbOsLpSqcq2xj0GfapcGbvHiHR0hlXTXU9cELnGObXSgDVs1UDpM4pPcFb2CrG7aFCFoULYSe9yBpsn7RepYzomAIrF9hEo2_v_877x7HkVGAMBFd9Ij70jp5DbVumTkZuM9vRG8uDNwaOCsvbsEvZlBjpR4JO0b508vUyKPFctA5O6yzfLKMhpRtcj61HrvWrMqx3BehO-fSM-hmQUd1clH5dD_xX4P9wtR1oPZxNS7bVgUiNnUPkGocqMVS5p0SYyowzz7yKHu8tIpaTAQLPIbePcU6ewtGCBUSzUVZZB7jl5Vte'
})
};
this.Http.get<Teacher>(this.API_URL + 'Teacher/GetTeachers', { headers: this.header }).subscribe(data => {
this.Results = data as Teacher;
console.log('Results' + this.Results[0]);
console.log(this.Results);
});
After sending this request i am getting the following error.
The requested resource does not support http method 'OPTIONS'
Can anyone please help me out.
I had similar issue previously and I forgot Enabling cors at my server side.
public static void Register(HttpConfiguration config)
{
// Forgot adding below line.
config.EnableCors();
}
Is it something that you can check in your WebApiConfig.cs?
i had a similar issue when i was working on the back end of an application while a colleague was doing the front end in angular. i believe we were using basic authentication.
in the end what worked was adding Access-Control-Allow-Methods to the web.config.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Authorization, authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
note: the above will allow prety much anything. you might want to limit the allow origin, and methods to what you need.
Edit: found the old code. i also made additions to Application_BeginRequest method in global.asax.cs
protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
hope it helps.
edit2: also found one more web.config change
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

ext js Form.Submit always returns failure

Good Morning All,
I am trying a very basic form.submit and for some reason it ALWAYS comes back as failure.
Also using a local webservice in .NET.
I must be missing something very basic... or maybe something with the way the data is coming back.
I have attached few pictures to show how I am attempting:
image1 - form.submit
image2 - service.cs
image3 - how I am returning result from .NET webservice locally
Apologies for the images... for some reason cutting and pasting code is not working.
Thank you!
Stephen
here is a picture of debugger in webservice
first row is var variable
second row (x2) is converted to json using JsonConvert.SerializeObject
lastly is a pictures of debugger from browser upon return
I also have been trying to understand CORS... so I added the following to my web.config which doesn't help
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
enter code here
here is firefox debugger
I adjusted my web.config to allow options and still get error
STATUS CODE 405 METHOD NOT ALLOWED
<system.webServer>
<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="OPTIONS, TRACE, GET, HEAD, POST, PUT" />
<!--<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />-->
</customHeaders>
</httpProtocol>
</system.webServer>
OKAY... I made some changes... I removed those lines from my web.config and added a Global.asax.cs page with the following:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
Now it seems to go through successfully, but still hits failure. Am I on to something here? Is it my json format?
result
Your response has backslashes, which is not valid JSON. It has to be {"success":true} without backslashes.
This should be due to double serialization. Where you debugged it, it's OK. But you should be serializing it one more time somewhere else. Make sure you avoid double serialization.

Categories

Resources