zoukankan      html  css  js  c++  java
  • 为Asp.net WebApi 添加跨域支持

     Nuget安装包:microsoft.aspnet.webapi.cors

    原文地址:https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    Enable CORS

    Now let's enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

    Install-Package Microsoft.AspNet.WebApi.Cors

    This command installs the latest package and updates all dependencies, including the core Web API libraries. User the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.

    Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.

    using System.Web.Http;
    namespace WebService
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // New code
                config.EnableCors();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }

    Next, add the [EnableCors] attribute to the TestController class:

    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Cors;
    
    namespace WebService.Controllers
    {
        [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
        public class TestController : ApiController
        {
            // Controller methods not shown...
        }
    }

    For the origins parameter, use the URI where you deployed the WebClient application. This allows cross-origin requests from WebClient, while still disallowing all other cross-domain requests. Later, I’ll describe the parameters for [EnableCors] in more detail.

  • 相关阅读:
    操作系统六文件管理
    Educational Codeforces Round 38 (Rated for Div. 2) ABCD
    51nod 1100 斜率最大
    51nod 最小方差
    51nod 1065 最小正子段和
    P1280 尼克的任务
    牛客小白月赛2
    Codeforces Round #210 (Div. 1) B 二分+dp
    江西财经大学第一届程序设计竞赛
    51nod 1596 搬货物
  • 原文地址:https://www.cnblogs.com/LongMarch/p/6148207.html
Copyright © 2011-2022 走看看