使Cors可以在线共享SharePoint

时间:2018-06-27 19:16:27

标签: ajax asp.net-web-api sharepoint cors sharepoint-online

我有一个共享点在线列表,我想在其中使用核心2的asp.net Web API

所以我在启动类中启用cors为:

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IEmailSender, EmailSender>();
            services.AddMvc();

            services.AddCors(options =>
            {
                options.AddPolicy("MyCorsPolicy", builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .WithHeaders("Accept", "Content-Type", "Origin", "X-My-Header"));
            });

        }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseCors("MyCorsPolicy");

            app.UseMvc();
        }

控制器:

[EnableCors("MyCorsPolicy")]
[Route("api/Email")]
    public class EmailController : Controller
    {...}

但是当我尝试在共享点中通过ajax调用使用api时,我得到了:

  

无法加载https://apiurl/api/email/send:对预检请求的响应未通过访问控制检查:   响应中的“ Access-Control-Allow-Origin”标头不得为   当请求的凭据模式为“包括”时,使用通配符“ *”。起源   因此,不允许访问“ https://shareapp.sharepoint.com”。的   XMLHttpRequest发起的请求的凭据模式为   由withCredentials属性控制。

请求:

<script>
$(document).ready(function() {
$.ajax({
 crossDomain: true,
 xhrFields: {
 'withCredentials': true
 },
 type: 'POST',
  data: { correo: "user@gmail.com"} ,
  contentType: 'application/json; charset=utf-8',
   url: 'apiurl/api/email/send'
 }).done(function (data) {
   console.log(data);
 }).error(function (jqXHR, textStatus, errorThrown) {
   console.log('oops');
});

});

</script>

任何人都知道我在那里可以做什么?问候

更新:

我从ajax中删除了'withCredentials': true,现在又遇到了另一个错误(500)

  

无法加载https://apiurl/api/email/send:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。因此,原点“ https://shareapp.sharepoint.com”不是   允许访问。响应的HTTP状态码为500。

实际要求:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$.support.cors = true;
$.ajax({
 crossDomain: true,
 type: 'POST',
 headers: {
                    Accept: "application/json;odata=verbose"
                },
                async: false,
  data: { correo: "user@gmail.com"} ,
  contentType: 'application/json; charset=utf-8',
   url: 'https://myapi/api/email/send'
 }).done(function (data) {
   console.log(data);
 }).error(function (jqXHR, textStatus, errorThrown) {
   console.log('oops');
});

});

</script>

控制器:

[EnableCors("MyCorsPolicy")]
    [Route("api/Email")]
    public class EmailController : Controller
    {
        private readonly IEmailSender _emailSender;


        public EmailController(IEmailSender emailSender)
        {
            _emailSender = emailSender;

        }

        [Route("Send")]
        [HttpPost]
        public IActionResult Index([FromBody] Email model)
        {
            _emailSender.SendEmailAsync(model.Correo, "Correo Sharepoint", "correo desde api");
            return new OkResult();
        }

0 个答案:

没有答案