简体   繁体   中英

Postman request with ASP.NET Core API call is unauthorized

I just created an ASP.NET Core application and I am trying to test a Web API call that creates an item using the following controller method below. But I am following the instructions on this page ( https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api ) which uses Postman to test the method.

[HttpPost]
[Route("api/asset")]
public IActionResult Create([FromBody] Asset asset)
{
    if (!ModelState.IsValid)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return null;
    }
    AssetItems.Add(asset);
    return CreatedAtRoute("GetAsset", new { id = asset.Id }, asset);
}

But when I make the request using Postman, I get the error:

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.

Check to see if authentication/authorization filter has been added to request pipeline. Could have been added based on the project template you used when creating project.

If the controller has an [Authorize] attribute then removing it should allow requests through.

If however the Authorize filter was added globally then you may need to add an [AllowAnonymous] attribute on the action or controller to let requests through for that action or controller.

[HttpPost]
[AllowAnonymous]
[Route("api/asset")]
public IActionResult Create([FromBody] Asset asset) { ... }

Check your launchsettings.json (if you're running the API from the Visual Studio debugger), or your web.config (if you're running the API from IIS).

In my case, I had:

    "windowsAuthentication": true,
    "anonymousAuthentication": false,

Updating "anonymousAuthentication" to true solved this issue for me.


I dont have a definitive reason as to why this solved the issue, but I believe your browser must acknowledge the fact you're authenticated on your machine and passes this to the API. However Postman does not know that you are authenticated on your local machine. Hopefully someone will be able to confirm if that's the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM