javascript - 如何设置 Origin 请求 header

标签 javascript jquery asp.net asp.net-web-api

我想向远程 API 发送 AJAX 请求。

function Gettest(CourseID) {
    var param = { "CourseID": CourseID};
    param = JSON.stringify(param);
    $.ajax({
        type: "Post",
        url: apiurl + "Course/DelCoursetargetedaudience",
        contentType: "application/json; charset=utf-8",
        data: param,
        dataType: "json",
        success: function (data) {
        },
        error: function (response) {
        }
    });
};

但我需要在发送请求之前更改原始名称。

请引用下图。

enter image description here

最佳答案

简而言之:你不能。

MDN 所述; Origin 是一个“禁止的” header ,这意味着您不能通过编程方式更改它。

您需要配置 Web 服务器以允许 CORS 请求。

要启用 CORS,请将其添加到您的 Web.config

<system.webServer>   
    <!-- Other stuff is usually located here as well... -->
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />               
        </customHeaders>
    </httpProtocol>
<system.webServer>

或者,在 Global.asax.cs 中

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        /* Some register config stuff is already located here */
    }

    // Add this method:
    protected void Application_BeginRequest()
    {
        HttpContext.Current.Response.AddHeader
            (name: "Access-Control-Allow-Origin", value: "*");            
    }
}

关于javascript - 如何设置 Origin 请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46808011/

相关文章:

javascript - 分割单个值

javascript - Atlassian 的 Jira 中的 CSS 类名被混淆了

javascript - 如果部分 url 匹配,则突出显示父菜单

javascript - 如何让 fullcalendar 读取日期/时间?

javascript - 使用 JavaScript 在文本字段中显示信息

javascript - 使用输入范围缩放谷歌地图

javascript - 获取 JQuery ui.draggable 的属性

c# - 将 SQL Server json 属性与代码优先 EF 一起使用

javascript - 使用 Javascript 进行 ASP.NET 复选框列表验证

c# - 如何从 ASP.NET 标记中获取资源字符串?