首页 文章

当发送承载令牌Angularjs Webapi2时,请求客户端总是发送方法选项

提问于
浏览
0

您好我已经使用C#中的WebAPI 2创建了一个API,我已经在api中启用了CORS并且具有令牌认证,并且我可以做几乎任何请求,例如 .

我有一个控制器用于测试,并有这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ApiJSON.Controllers
{
    public class PruebaController : ApiController
    {
        // GET: api/Prueba
        [AllowAnonymous]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Prueba/5
        [Authorize]
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Prueba
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/Prueba/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Prueba/5
        public void Delete(int id)
        {
        }
    }
}

如果我向任何客户提出请求,如Fiddler或Advance Rest Client,使用方法GET到api / Prueba,无需令牌工作完美,而api / Prueba / 5发送持票令牌,它也会返回完美,但是当我从客户端打电话时在angular,总是发送方法OPTIONS并拒绝承诺,我尝试从chrome和firefox尝试使用$ http,Restangular和JQuery REST Client,但始终使用相同的结果 .

谢谢大家 .

UPDATE

这是Chrome中的控制台显示的内容,在Firefox中没有显示任何内容:

cannot load http://localhost:49950/api/prueba/. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

UPDATE

我以这种方式在WebApiConfig.cs中启用了CORS:

public static void Register(HttpConfiguration config)
        {
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        }

按照建议,我以这种方式在控制器中添加了EnableCors:

// GET: api/Prueba/5
        [Authorize]
        [EnableCors(origins:"*", headers:"*", methods:"*")]
        public string Get(int id)
        {
            return "value";
        }

我在Startup.cs中看到的东西,我正在以这种方式使用Microsoft.Owin.Cors:

public void Configuration(IAppBuilder app)
        {

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new MyAuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);


            //ConfigureAuth(app);
            //app.MapSignalR();
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration { };
                map.RunSignalR(hubConfiguration);
            });


        }

也许它干扰了System.Web.Http.Cors再次感谢您的帮助 .

UPDATE

我已经找到了问题,在Global.asax我需要指定 Headers ,这是我把它和工作正常的方式 .

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

这是我添加的一段代码:

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization");

谢谢你的回答,我希望它可以帮助别人 .

1 回答

相关问题