我在努力做什么

我有一个后台ASP。Net Core Web API托管在Azure免费计划上(源代码:https://github.com/killerrin/Portfolio-Backend)。

我也有一个客户端网站,我想让消费该API。客户端应用程序不会托管在Azure上,而是托管在Github Pages或我可以访问的其他Web托管服务上。正因为如此,域名不会排成一行。

研究这个问题,我需要在Web API端启用CORS,但是我已经尝试了几个小时,现在它拒绝工作。

我如何有客户端设置 它只是一个用React.js编写的简单客户端。我通过Jquery中的AJAX调用api。React网站工作,所以我知道它不是。Jquery API调用工作,我在尝试1确认。我是这样打电话的

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });

我所尝试过的


尝试1 -“正确”的方式

https://learn.microsoft.com/en-us/aspnet/core/security/cors

我已经遵循微软网站上的本教程,尝试在Startup.cs中全局启用它的所有3个选项,在每个控制器上设置它,并在每个动作上尝试它。

按照这种方法,跨域工作,但只能在单个控制器上的单个动作上工作(POST到AccountController)。对于其他任何事情,Microsoft.AspNetCore.Cors中间件拒绝设置头文件。

我通过NUGET安装了Microsoft.AspNetCore.Cors,版本为1.1.2

下面是我如何在Startup.cs中设置它

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure 
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }

如你所见,我都是照做的。我两次都在MVC之前添加了Cors,当这不起作用时,我尝试在每个控制器上都添加[EnableCors(“MyPolicy”)]

[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller

尝试2 -暴力强迫它

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

在尝试了几个小时的前一次尝试后,我认为我应该尝试手动设置头,强制它们在每个响应上运行。我在本教程中介绍了如何手动为每个响应添加标题。

这些是我添加的头文件

.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")

这些是我尝试失败的其他头

.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")

有了这个方法,跨站点的头被正确地应用,他们显示在我的开发控制台和邮差。然而,问题是,当它通过访问控制-允许起源检查时,web浏览器抛出了一个嘘声(我相信)访问控制-允许头部声明415(不支持的媒体类型)

所以暴力法也不管用


最后

有没有人得到了这个工作,可以伸出手来,或者只是能够指出我在正确的方向?


EDIT

因此,为了让API调用顺利进行,我不得不停止使用JQuery,转而使用纯Javascript的XMLHttpRequest格式。

尝试1

我设法让Microsoft.AspNetCore.Cors通过遵循MindingData的答案工作,除了在配置方法中将app.UseCors放在app.UseMvc之前。

此外,当与Javascript API解决方案options.AllowAnyOrigin()混合时,通配符支持也开始工作。

尝试2

所以我已经设法让尝试2(暴力强迫它)工作…唯一的例外是,通配符访问控制-允许-起源不工作,因此我必须手动设置有权限访问它的域。

这显然不是理想的,因为我只是想让这个WebAPI对每个人都开放,但它至少在一个单独的网站上为我工作,这意味着它是一个开始

app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));

看看下面两种方法:

public static void foo() {
    try {
        foo();
    } finally {
        foo();
    }
}

public static void bar() {
    bar();
}

运行bar()显然会导致StackOverflowError,但运行foo()不会(程序似乎无限期地运行)。为什么呢?

我有两个WebApp1和WebApp2在两个不同的域。

我在WebApp1的HttpResponse中设置了一个cookie。 如何从WebApp2中的HttpRequest读取相同的cookie ?

我知道这听起来很奇怪,因为cookie是特定于给定域的,我们不能从不同的域访问它们;不过我听说过跨域cookie,它可以在多个web应用程序之间共享。如何使用跨域cookie实现这一需求?

注意:我正在尝试使用J2EE web应用程序

我有一个标准的重置按钮的形式编码如下:

<input type="reset" class="button standard" value="Clear" />

问题是,所述表单是多阶段排序的,所以如果用户填写了一个阶段,然后稍后返回,当单击Clear按钮时,各个字段的“记住”值不会重置。

我在想,附加一个jQuery函数循环所有的字段和清除他们'手动'将做的技巧。我已经在使用jQuery的形式,但我只是刚刚赶上速度&所以我不知道如何做到这一点,除了单独引用每个字段的ID,这似乎不是很有效。

请TIA帮忙。

我有工作代码,可以重置我的表单时,我点击重置按钮。然而,当我的代码变长后,我意识到它不再工作了。

<div id="labels">
  <table class="config">
    <thead>
      <tr>
        <th colspan="4"; style= "padding-bottom: 20px; color:#6666FF; text-align:left; font-size: 1.5em">Control Buttons Configuration</th>
      </tr>
      <tr>
        <th>Index</th>
        <th>Switch</th>
        <th>Response Number</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>            
      <form id="configform" name= "input" action="#" method="get">
        <tr>
          <td style="text-align: center">1</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" value="" id="number_one"></td>
          <td><input style="background: white; color: black;" type="text"  id="label_one"></td>
        </tr>
        <tr>
          <td style="text-align: center">2</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" id = "number_two" value=""></td>
          <td><input style="background: white; color: black;" type="text"  id = "label_two"></td>
        </tr>
        <tr>
          <td style="text-align: center">3</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" id="number_three" value=""></td>
          <td><input style="background: white; color: black;" type="text" id="label_three"></td>
        </tr>
        <tr>
          <td style="text-align: center">4</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" id="number_four" value=""></td>
          <td><input style="background: white; color: black;" type="text" id="label_three"></td>
        </tr>
        <tr>
          <td></td>
          <td><input type="submit" id="configsubmit" value="Submit"></td>
        </tr>
        <tr>
          <td><input type="reset" id="configreset" value="Reset"></td>
        </tr>
                  
      </form>
    </tbody>
  </table>
            
</div>

和我的jQuery:

$('#configreset').click(function(){
    $('#configform')[0].reset();
});

是否有一些源代码,我应该包括在我的代码中,以使.reset()方法工作?之前我用的是:

<script src="static/jquery.min.js"></script>
<script src="static/jquery.mobile-1.2.0.min.js"></script>

并且.reset()方法正在工作。

目前我正在使用

<script src="static/jquery-1.9.1.min.js"></script>      
<script src="static/jquery-migrate-1.1.1.min.js"></script>
<script src="static/jquery.mobile-1.3.1.min.js"></script>

这可能是原因之一吗?

我在做一个Ajax。请求一个远程PHP服务器在Sencha Touch 2应用程序(包装在PhoneGap)。

服务器的响应如下:

XMLHttpRequest无法加载http://nqatalog.negroesquisso.pt/login.php。Access-Control-Allow-Origin不允许Origin http://localhost:8888。

我该如何解决这个问题?

我认为两者都在做同样的工作,您如何决定使用哪一个进行同步呢?

我想强制一个表的自动增量字段的一些值,我尝试了这样:

ALTER TABLE product AUTO_INCREMENT = 1453

AND

ALTER SEQUENCE product  RESTART WITH 1453;
ERROR:  relation "your_sequence_name" does not exist

我有一个表产品与Id和名称字段

Bootstrapcdn最近改变了他们的链接。现在看起来是这样的:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" 
rel="stylesheet" 
integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" 
crossorigin="anonymous">

完整性和交叉源属性是什么意思?它们如何影响样式表的加载?

这里有两个页面,test.php和testserver.php。

test.php

<script src="scripts/jq.js" type="text/javascript"></script>
<script>
    $(function() {
        $.ajax({url:"testserver.php",
            success:function() {
                alert("Success");
            },
            error:function() {
                alert("Error");
            },
            dataType:"json",
            type:"get"
        }
    )})
</script>

testserver.php

<?php
$arr = array("element1",
             "element2",
             array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>

现在我的问题是:当这两个文件都在同一服务器(本地主机或web服务器),它的工作和警报(“成功”)被调用;如果它在不同的服务器上,即web服务器上的testserver.php和localhost上的test.php,则它不工作,并且alert(“错误”)正在执行。即使AJAX内部的URL更改为http://domain.example/path/to/file/testserver.php