Search code examples
vb.netasp.net-web-apicors

How to enable CORS in vb.net web API project


Environment: Microsoft Visual Studio 2019 Community, ASP.NET v4.8 web application/web API project using VB.NET

I can find lots of C# answers to this but no vb.net answers. I have added the CORS Nuget packages to my project and added this code (it compiles and runs ok but makes no difference on localhost or prod i.e. any origin domain can still call the POST method):

WebApiConfig.vb

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web.Http
Imports System.Web.Http.Cors

Public Module WebApiConfig
    Public Sub Register(ByVal config As HttpConfiguration)
        ' Web API configuration and services
        Dim corsAttr = New EnableCorsAttribute("http://example.com", "*", "*")
        config.EnableCors(corsAttr)

Controller:

' POST: api/Notification
<EnableCors("https://www.somedomain.com", "*", "*")>
Public Function PostValue(<FromBody()> ByVal value As Object)

Solution

  • Here's a very quick rundown of a CORS controlled, in a normal, honest browser just installed fresh off Mozilla/Google's website:

    • page is served from acme.com
    • page contains script
    • script wants data from foobar.com, asks browser to GET the data
    • browser first says "hey foobar.com, what are the list of websites that you will let download your data?"
    • foobar.com says "foobar.com and barbaz.com"
    • browser denies script's attempt to get, because script was served from acme.com and acme.com is not in the list of permitted sites

    If foobar.com had responded nominating acme.com as being in the list of sites, then the browser would have proceeded to actually perform the GET


    Postman doesn't care about any of that; if you ask Postman to get data from foobar.com it will make the request, foobar.com will probably* serve it and postman will show it..

    *technically it could be possible for the server to refuse to serve it but CORS is not a server side security feature; it relies on decent, honest browsers blocking the request if told to do so