Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable cross origin requests in ASP.NET MVC 4 on POST using Angular 2

I'm trying to make a POST request with CORS.

I've a class that adds the correct response header on my methods inside my controller

using System;
using System.Web.Mvc;

public class AllowCrossSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");

        base.OnActionExecuting(filterContext);
    }
}

and I use it like this

[AllowCrossSite]
public ActionResult GetReportParameters(string IdRapport)

and I get the expected result enter image description here

But the problem is when I'm trying to make a POST request with a custom header to pass this specific content type

'Content-Type': 'application/json; charset=utf-8'

I'm actually getting these Response headers

enter image description here

So it's like nothing is done about the header even if I'm correctly going in my attribute class.

Here is my front side in Angular 2 service

const headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' });
const options = new RequestOptions({ headers: headers , withCredentials: true });

const mock = {
  name: 'TitreRegroupement1',
  visible: false,
  type: 'System.String',
  value: 'Test'
};

// tslint:disable-next-line:max-line-length
const body = JSON.stringify({ idRapport: '00392024-d171-4f39-9c5c-97a51f53fd54', filtre: '', exportFormat: '', parameters: data });

return this.http.post('http://localhost:8080/ReportingViewer/ExportReport', body, options)
  .map((response: Response) => {
      return this.extractSingleData(response, Parameters);
  })
  .catch(this.handleError);
}

By using postman there is no problem to declare, the whole thing travel correctly I can access my parameters from the method inside the controller with no problem.

like image 453
Fitch Avatar asked May 11 '17 10:05

Fitch


People also ask

How to enable cross origin request in ASP NET Web API?

By default, cross origin request is disabled in ASP.NET Web API. But when we need call ASP.NET Web API, then it needs to be enabled. We will focus more on our ASP.NET Web API than Mobile Application in this article. Figure: Request overview between Mobile App and Web API. Firstly, we will create a database.

What is Cors (enable cross-origin requests)?

Enable Cross-Origin Requests (CORS) in ASP.NET Core. Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site.

What is Cross-Origin Resource Sharing in ASP NET?

Cross (Cross-origin resource Sharing) is a World Wide Web Consortium. Basically, it is considered part of HTML5. Mobile app will call XML Http Request for Http verb (GET, POST, PUT, Delete, etc.) to the ASP.NET Web Application, using API. By default, Cross origin Request is disabled in ASP.NET Web API.

How to allow cross-origin credentials in web API?

To allow cross-origin credentials in Web API, set the SupportsCredentials property to true on the [EnableCors] attribute: If this property is true, the HTTP response will include an Access-Control-Allow-Credentials header. This header tells the browser that the server allows credentials for a cross-origin request.


1 Answers

I found how to make it work. First I apply what proposed me sideshowbarker

if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OridinalIgnoreCase) &&
    Request.HttpMethod == "OPTIONS") {
    Response.Flush();
}

and I was missing something in my Headers, I was doing "*" all the way but finally with these parameters it worked

filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

for those who are interested in the final form of my class here it is

using System;
using System.Web;
using System.Web.Mvc;

namespace Via.Client.WebMvc
{
    public class AllowCrossSiteAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {    
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");

            if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
            {
                filterContext.HttpContext.Response.Flush();
            }

            base.OnActionExecuting(filterContext);
        }
    }
}
like image 72
Fitch Avatar answered Oct 12 '22 04:10

Fitch