Setting up cross domain access in MVC


1. What is cross domain request

JS forbids sending an Ajax request to a website that is not the current domain name. Even if the data is successfully responded, your JS will still report an error. This is the same origin policy limitation of JS. It is not the programming problem of our website that JS controls. Both client (web page) and background programming can effectively solve this problem. The client can complete cross domain access through jsonp. In ES6, in order to solve the problem of the same origin policy, a method is proposed: when the requested website adds a header named access control allow origin to the response header, and sets its value equal to the domain name address of the requesting website, the request is considered to be allowed. Where the value of access control allow origin is * to allow cross domain requests for all websites.

This article explores how to set up cross domain access in the background code.

2. Add code in action

HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");

3. Add application configuration in webconfig:

<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="*" />

4. Add action filter

No matter the action of webapi or MVC, we can override the onexception method of actionfilterattribute filter to add a header for the HTTP response after the action is executed; the onexception method means the operation after the action is executed. This filter can be added to the action or controller, but it needs to be applied to every action or controller. Here, we add the action filter we rewrite to the global filter, so that every action will trigger this filter after the completion of execution. Here, take webapi as an example. New class:

/// <summary>
  // cross domain
  /// </summary>
  public class Cores:ActionFilterAttribute
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

Add in webapiconfig.

public static class WebApiConfig
    public static void Register(HttpConfiguration config)
      //Web API configuration and services
      //Configure the web API to use only anonymous token authentication.
      config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
      //Web API routing
      config.Filters.Add(new Cores());
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }


The above is the cross domain access problem in MVC that Xiaobian introduced to you. I hope it can help you. If you have any questions, please leave a message to me, and Xiaobian will reply you in time. Thank you very much for your support of the developepaer website!