简体   繁体   English

未经授权的消息,状态为200 OK

[英]Unauthorized Message,Status 200 OK

I am doing the backend according to the given architecture given by the company I recently started working. 我正在根据我最近开始工作的公司给出的给定体系结构来做后端。 I am new to C# and now I'm trying to do some post/get/put methods for some api-s. 我是C#的新手,现在我正尝试为一些api-s做一些post / get / put方法。 There is a problem which I couldn't solve it. 有一个我无法解决的问题。 Postman says: { "code": 1, "message": "Unauthorize" } But the status code is 200 OK. 邮递员说:{“代码”:1,“消息”:“未授权”}但是状态代码为200 OK。

UserController.cs UserController.cs

[Route("v1/users")]
[Produces("application/json")]
public class UserController : BaseController
{
    /// <summary>
    ///     Get list of users (Authorize)
    /// </summary>
    /// <returns>
    /// </returns>
    [ProducesResponseType(typeof(BaseResponseModel<List<UserResource>>), 200)]
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var user = await _userService.GetUserResourcesAsync();

        return Success(user);
    }
 }

This doesn't make any sense, or am I so dumb to realise the problem? 这没有任何意义,还是我很愚蠢地意识到了问题? I have a login method and I can login, I get the success code, then I do this: enter image description here Header 我有一个登录方法,我可以登录,我得到了成功的代码,那么我这样做: 在这里输入的形象描述

IProductService.cs IProductService.cs

    public interface IProductService
{
    Task<ProductDto>  GetAsync(int id);
}

ProductService.cs ProductService.cs

        public async Task<ProductDto> GetAsync(int id)
    {
        var product = await _context.Product.SingleOrDefaultAsync(p => p.Id == id);
        return _mapper.Map<ProductDto>(product);

    }

ProductDto.cs ProductDto.cs

 public class ProductDto
{
    public int Id { get; set; }

    public CategoryDto CategoryId { get; set; }

    public string Title { get; set; }

    public bool AllowEdit { get; set; }

    public string ItemCode { get; set; }

    public string CustomerCode { get; set; }
 }

Product.cs 产品.cs

[Table("Products")]
public class Product : DomainModel<int>
{
    [Required]
    public int ProductCategoryId { get; set; }

    [ForeignKey("ProductCategoryId")]
    public virtual ProductCategory ProductCategory { get; set; }

    [Required, StringLength(256)]
    public string Title { get; set; }

    [Required, DefaultValue(false)]
    public bool AllowEdit { get; set; }

    [StringLength(50)]
    public string ItemCode { get; set; }

    [StringLength(50)]
    public string CustomerCode { get; set; }
}

Using the ProducesResponseTypeAttribute , the attributed API actually defines what should be response code for specified types. 通过使用ProducesResponseTypeAttribute ,属性API实际上定义了指定类型的响应代码。 See the definition of at ProducesResponseTypeAttribute . 请参阅ProducesResponseTypeAttribute的定义。

How it works 这个怎么运作

Take following example which shows that the API throws the 404 error if the object is null: 采取以下示例,该示例显示如果对象为null,则API会引发404错误:

public IActionResult GetById(string id)
{
    var post = <<Your logic here>>;
    if (post == null)
    {
        return NotFound();
    }

    return Json(post);
}

Now the same method can be changed to following, which would return 404 by using the ProducesResponseType instead of the code is being written in your API logic. 现在,可以将相同的方法更改为以下方法,该方法将通过使用ProducesResponseType返回404,而不是在API逻辑中编写代码。

[ProducesResponseType((int)HttpStatusCode.NotFound)]
public IActionResult GetPostById(string id)
{
        var post = <<Your logic here>>;
        return Json(post);
    }

在此处输入图片说明

In cases, it might be good to also define a more explicit response type for successful calls. 在某些情况下,最好为成功的调用定义一个更明确的响应类型。 To do so, add a ProducesResponseTypeAttribute for status code with type. 为此,为带有类型的状态代码添加ProducesResponseTypeAttribute ( return type as parameter, which makes the Type property of Produces redundant). (将返回类型作为参数,这将使Produce的Type属性产生冗余)。 This is valuable, if you want to return different things from one and the same method, for example, the following returns two different types depending on the returned status code: 这很有价值,例如,如果您想从一个相同的方法返回不同的内容,则以下代码根据返回的状态码返回两种不同的类型:

[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesResponseType(typeof(Model), (int)HttpStatusCode.OK)]
public IActionResult GetById(string id)

What is your problem 你有什么问题

Now if you see your code which defines this attribute as [ProducesResponseType(typeof(BaseResponseModel<List<UserResource>>), 200)] . 现在,如果您看到将此属性定义为[ProducesResponseType(typeof(BaseResponseModel<List<UserResource>>), 200)] And the code to fetch user : 和获取用户的代码:

var user = await _userService.GetUserResourcesAsync();

returns BaseResponseModel<T> . 返回BaseResponseModel<T> The BaseResponseModel should contain the Code and Message property. BaseResponseModel应该包含CodeMessage属性。 So here, the response returned by API is type of BaseResponseModel<T> , so API would return 200 HTTP Status as defined by attribute. 因此,在这里,API返回的响应是BaseResponseModel<T>类型,因此API将返回200 HTTP状态(由attribute定义)。

How to Fix 怎么修

Either you return a different object in case of Unauthorize exception and attach the ProducesResponseType specific to that type OR handle the unathorized logic based at Authorize attribute. 如果发生Unauthorize异常,则返回另一个对象,并附加特定于该类型的ProducesResponseType ,或处理基于Authorize属性的未Authorize逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ajax发布formdata错误状态200 OK - ajax posting formdata error status 200 OK JQuery AJAX,错误状态代码:200,状态文本:parserorro | 好 - JQuery AJAX, Error Status code: 200, Status Text: parserorro | OK 尽管状态为200 OK,为什么AJAX JSON响应仍失败? - Why is AJAX JSON response failing despite 200 OK status? 相同状态代码 200OK 的多个 ProducesResponseType - Multiple ProducesResponseType for same status code 200OK 在 Api 的 Ok ()(状态 200)中返回 json 的最佳方法是什么? - what is the best way to return a json in an Ok () (status 200) of an Api? 如果状态码不等于 200 OK 使用 Polly 重试 api 请求 - Use Polly to retry api request if the status code is not equal to 200 OK 使用http 200响应+自定义消息来处理我的未授权请求 - handling my unauthorized requests , with an http 200 response + custom message 带有OK(200)代码的CreatedAtRoute - CreatedAtRoute with OK(200) code http状态代码200返回预期结果。 但是,当状态为BadRequest或未经授权时,我的C#webapi 1返回text / html - http status code 200 returns expected result. But when status is BadRequest or Unauthorized, my C# webapi 1 is returning text/html ASP.NET 获取 Web HTTP 状态为 NOT 200 时的响应 OK - ASP.NET Get Web Response when HTTP Status is NOT 200 OK
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM