【问题标题】:Issue in angularjs2 with restful web API带有restful Web API的angularjs问题
【发布时间】:2017-05-14 14:27:59
【问题描述】:

我正在使用 Restful Web API 做 AngularJS2,并在调用 HTTP 发布时遇到一些控制台错误。下面列出了错误,

希望对你有所帮助

控制器代码sn-p

namespace SoomWebApi.Controllers
{
    [EnableCors(origins: "http://localhost:64336", headers: "*", methods: "*")]
    public class UserController : ApiController
    {

        public HttpResponseMessage UserLogin([FromBody] LoginRequestData objValidate)
        {
            UserModelManager _UserModelManagerr = new Models.UserModelManager();

            return Request.CreateResponse(HttpStatusCode.OK, _UserModelManagerr.Login(objValidate), GetJSONFormatter());

        } 
    }
}

Webapiconfig 代码 sn-p

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        // Web API routes
        config.MapHttpAttributeRoutes();

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

【问题讨论】:

  • 请参考Old Post,这将帮助您解决第一个错误..

标签: c# angular asp.net-web-api asp.net-web-api2


【解决方案1】:

它看起来像一个 CORS 问题.. 尝试在 WebAPI 中放入您的 Startup.cs 文件,例如:

 using Microsoft.Owin;
using Owin;

 public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            ConfigureAuth(app);

        }

如果您想限制某些特定主机..尝试类似:

  var corspolicy = new corspolicy
            {
                allowanymethod = true,
                allowanyheader = true,
                supportscredentials = true,
                origins = { "http://www.example.com", "http://localhost:38091", "http://localhost:39372" }

            };

            app.usecors(new corsoptions
            {
                policyprovider = new corspolicyprovider
                {
                    policyresolver = context => task.fromresult(corspolicy)
                }
            });

【讨论】:

  • 允许一切对开发环境有利,但在生产模式下进行适当的配置。
  • 在 App_Start 文件夹中创建了一个 Startup.cs,并包含了您的代码。但找不到像 UseCors 这样的扩展
  • 您不必创建它... webapi asp.net 脚手架为您完成它(int 在 app_start 中..但在根路径中)..您需要安装 Nuget 包..尝试输入 nuget UI ...owin CORS
  • 不,您没有以正确的方式将其放入正确的文件中
【解决方案2】:

您的服务器应支持 CORS 以允许来自不同域的访问。更新您的服务器配置以仅允许预定义的域集允许访问。

Access-Control-Allow-Origin: "domains"

如果您仅在调试时遇到此问题并且不打算在部署后使用 CORS - 主要是本地 Web 服务器在 localhost:some-port 上启动您的 Angular 应用程序,并且服务器也部署在 localhost 上 - 使用 IE用于调试 - 即使您的 Angular 中间件和后端在不同的端口上工作,它也能正常工作。

【讨论】:

    【解决方案3】:

    如果生产中的代码将与 REST API 在同一个域中,您可以安装 chrome 扩展以避免 CORS 错误:

    Chrome CORS extension

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 2013-05-26
      • 2014-02-25
      • 2015-10-21
      • 1970-01-01
      • 2014-12-07
      相关资源
      最近更新 更多