Setting cross domain access issues in ASP. NET MVC

  • 2021-10-25 06:23:44
  • OfStack

1. What is a cross-domain request

js forbids to initiate an ajax request to a website that is not the current domain name. Even if respone is successful, your js will still report an error. This is JS homologous policy restrictions, JS control is not our website programming problems. Both client (web page) and background programming can effectively solve this problem. Clients can complete cross-domain access through JSONP; In order to solve the homologous policy problem in ES6, a method is proposed: when the requested website adds an header named Access-Control-Allow-Origin to the response header respone, and the value is set to be equal to the domain name address of the website that initiated the request, the request is considered allowed. Where the value of Access-Control-Allow-Origin is * to allow cross-domain requests for all Web sites.

This article mainly explores how to set cross-domain access in background code.

2. Add code to action


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

3. Add application configuration to webconfig:


<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>

4. Add action filter

Regardless of webapi or action of mvc, we can override OnException method of ActionFilterAttribute filter to add header header to http response after action execution is completed; The OnException method means the operation that takes place after action execution completes. This filter can be added to action or controller, but it is necessary to put this filter on every action or controller. Here, the action filter we rewrote is added to the global filter, so that every action will trigger this filter after the execution is completed. Here, take webapi as an example. New class:


  /// <summary>
  ///  Cross-domain 
  /// </summary>
  public class Cores:ActionFilterAttribute
  {
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
      base.OnActionExecuted(actionExecutedContext);
      actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
    }
  }

Added in webapiconfig.


  public static class WebApiConfig
  {
    public static void Register(HttpConfiguration config)
    {
      // Web API  Configuration and Services 
      //  Will  Web API  Configured to use bearer token authentication only. 
      config.SuppressDefaultHostAuthentication();
      config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
      // Web API  Route 
      config.MapHttpAttributeRoutes();
      config.Filters.Add(new Cores());
      config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
      );
    }
  }

Summarize


Related articles: