How to allow internal MVC Web Api from external site outside the network

前端 未结 2 1231
星月不相逢
星月不相逢 2020-11-29 12:56

I have a MVC Web API (hosted in IIS) which is in the wwwroot folder and locally accessible within the network.I can execute api calls like this: http://mylocalapi:133/

相关标签:
2条回答
  • 2020-11-29 13:25

    Add below code in your WebApiConfig class in in Register method

    config.EnableCors();
    
    0 讨论(0)
  • 2020-11-29 13:45

    You cannot access an internal-only site from JavaScript, as JavaScript runs client-side, on the end-user's machine, outside of your internal network. The only way to hit the API via JavaScript is to either 1) expose the API to the external network or 2) create a proxy within your external site.

    The proxy would be basically an action or actions that offer external access, and then translate the calls to your internal API. At the simplest, you could have a single action that basically responds to something like:

    https://foo.com/api?endpoint=/internal/api/endpoint/&someParam=foo
    

    The action would then take this information in the query string and use that to make a request to your internal API via something like HttpClient. However, this approach pretty much exposes your whole internal API, so you might as well just move it outside at that point. The better approach would be to create specific endpoints (action methods) for specific internal API calls you need to make via JavaScript.

    UPDATE

    It's difficult to give you any real direction here without context. Let's say that there's an internal API endpoint that returns a list of widgets and you want to retrieve this list of widgets via AJAX. You would need something like:

    public async Task<ActionResult> GetWidgets()
    {
        // fetch widgets from internal API via HttpClient
        return Json(widgets, JsonRequestBehavior.AllowGet);
    }
    

    Then, your AJAX would call the URL for this action method on your website, which under the hood calls the internal API.

    0 讨论(0)
提交回复
热议问题