【问题标题】:EnableCors working with ApiController but not with Controller .NET Framework 4.7.2EnableCors 使用 ApiController 但不使用 Controller .NET Framework 4.7.2
【发布时间】:2021-05-17 14:13:35
【问题描述】:

在我的项目中,我有 2 种控制器

  1. 公共类 BaseApiController : ApiController
  2. 公共类 BaseController:控制器

从 Angular 我能够访问 APIControllers 但无法访问控制器。收到阻止跨域请求的错误。 虽然启用了跨域,因为我可以访问 APIControllers。

var cors = new EnableCorsAttribute(
            origins: "*",
            headers: "*",
            methods: "*");
        config.EnableCors(cors);

知道访问控制器还需要什么其他设置。

提前致谢。

【问题讨论】:

  • 您是否尝试在 web.config 中添加“Access-Control-Allow-Origin”?
  • OPTIONS 请求是否成功?
  • @Giox,是的,我也试过了,但根本没有工作,即使 APIController 停止工作。
  • @CaiusJard,是的,APIControllers OPTIONS 请求返回 200,但控制器没有

标签: c# .net cross-domain


【解决方案1】:

我从这个 URL 得到了 @Fitch 建议的解决方案。 How to enable cross origin requests in ASP.NET MVC

如下创建一个类

using System;
using System.Web.Mvc;

public class AllowCrossSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");

        base.OnActionExecuting(filterContext);
    }
}

并添加如下属性。

    [Helpers.AllowCrossSite]
    public JsonResult GetDetails()
    {
        return Json(new
        {
            name = "",
            address = "",
            // ... more properties
        }, JsonRequestBehavior.AllowGet);
    }

【讨论】:

  • @CaiusJard,不应该有那些多余的空格,发布答案时好像出了点问题,我已经更正了。
猜你喜欢
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 2022-12-04
  • 1970-01-01
相关资源
最近更新 更多