首页 > 解决方案 > 从 WCF 服务调用 Web API Core 时出现 401 错误

问题描述

我正在尝试从 WCF 服务调用 .net 核心 Web api。

这是我的代码:

  var client = new HttpClient();

    
        client.BaseAddress = new Uri("http://...");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
   
        HttpResponseMessage response = await client.GetAsync("api/tasks");
            return await response.Content.ReadAsStringAsync();
     

响应返回 401 错误:未经授权。

我的 web api 支持 windows 和匿名身份验证,我在允许的 cors 来源中添加了“*”:

   services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()
       
           .WithOrigins("http://localhost:4200","http://...", "*");
        }));

我的 web api 控制器中的 get 函数是:

  // GET api/tasks
    [AllowAnonymous]
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

仍然是相同的错误响应。知道为什么吗?

标签: wcfasp.net-core-webapihttp-status-code-401

解决方案


我认为您的网址中有错误。

尝试这个:

 HttpResponseMessage response = await client.GetAsync("api/tasks/get");

推荐阅读