Zerry Hogan
Zerry Hogan

Reputation: 193

Enable CORS on Specific URL in ASP.NET Web Forms

I'm not a backend developer, so I apologize ahead of time if I do not provide enough information. I am just trying to find some resources that will help my backend developer understand what I am trying to do.

I am trying to make an AJAX GET request to an rss feed inside of web application that was built using ASP.NET Web Forms. However, the request gets blocked because of Cross Origin Security. I want to enable CORS for the route that is associated with our RSS feed (/page/rss/{id}).

I was able to enable CORS in our webconfig using:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" values="*" />
        <add name="Access-Control-Allow-Methods" values="GET" />
        <add name="Access-Control-Allow-Headers" values="Content-Type" />
   </customHeaders>
</httpProtocol>

But, that enables it for the entire project which is not what I want. Our routes are defined in an XML file like this:

<namespace.routing>
  <routings>
    <route name="publishedPage" url="page/{PageName}" page="~/Default.aspx" />
  </routings>
  <defaults>
    <default url="http://blog.example.com" domain="example.com" page="page/homepage" />
  </defaults>
</namespace.routing>

So, how would one go about enabling CORS on a specific path in ASP.NET Web Forms? If someone could point me in the direction of some resources that would help us that would be great. If you need anymore information I'm happy to provide it. Thanks!

Upvotes: 3

Views: 9511

Answers (1)

supersighs
supersighs

Reputation: 947

I'm not sure how you are returning your rss endpoint, but if you have access to the HttpContext object, you can use it to supply the CORS headers directly.

HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Methods", "Get");
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type");

Depending on how old your app is, you might need to use AddHeader instead of AppendHeader.

Upvotes: 5

Related Questions