C# 发送承载令牌Angularjs Webapi2时,请求客户端始终发送方法选项

C# 发送承载令牌Angularjs Webapi2时,请求客户端始终发送方法选项,c#,angularjs,rest,asp.net-web-api2,bearer-token,C#,Angularjs,Rest,Asp.net Web Api2,Bearer Token,您好,我已经用C#中的WebAPI 2制作了一个API restful,我已经在API中启用了CORS并进行了令牌身份验证,我几乎可以对这个进行任何请求,例如 我有一个控制器进行测试,并有这个 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ApiJSON.Con

您好,我已经用C#中的WebAPI 2制作了一个API restful,我已经在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)
        {
        }
    }
}
根据建议,我在控制器中以这种方式添加了EnableCor:

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);
        }
// GET: api/Prueba/5
        [Authorize]
        [EnableCors(origins:"*", headers:"*", methods:"*")]
        public string Get(int id)
        {
            return "value";
        }
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);
            });


        }
我正在观看Startup.cs中的一些内容,在那里我以以下方式使用Microsoft.Owin.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);
        }
// GET: api/Prueba/5
        [Authorize]
        [EnableCors(origins:"*", headers:"*", methods:"*")]
        public string Get(int id)
        {
            return "value";
        }
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再次感谢您的帮助

更新

我已经发现了问题,在Global.asax中,我需要指定标题,这是我放置标题的方式,工作正常

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(“访问控制允许头”,“授权”)


谢谢您的回答,我希望它能帮助其他人。

假设您使用的是Microsoft.AspNet.WebApi.Cors软件包

实际上,您需要在控制器(或操作)上使用
EnableCors
属性或在config类中全局启用CORS。上述代码中似乎缺少该属性


这可能有助于查看浏览器上的网络控制台,它会告诉您失败的原因。感谢您的回答,但它仍然拒绝了请求。