nefosfatus
nefosfatus

Reputation: 89

How to create ASP.NET Core Web API properly

I little unsure of my actions. I started my first web api application. So I wanna create api where is all functionality include authorization. And web and mobile applications which will work with my api. Something like that

But I discover problem on authorization step. I must handle many api's response variation like 401(unauthorized),200(OK) etc. I get response in Json format. And every response have own structure and its structure changes in differet cases. So that is the problem I can miss handle something and crash my app. How can I avoid it. May be I missunderstand something. I will be greateful for any help.

I create API on asp.net core framework.

Some response examples

OK 200 {"result":{"succeeded":true,"isLockedOut":false,"isNotAllowed":false,"requiresTwoFactor":false},"token":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiI5YjkwZDFmZC1iMjQzLTRhMTEtYWQ3NS1iZWU0ZDJjNTJhNTEiLCJ1bmlxdWVfbmFtZSI6IkVlZm9zZmF0dXMxMzNAZ21haWwuY29tIiwibmJmIjoxNTkzOTU4MjM4LCJleHAiOjE1OTQwNDQ2MzgsImlhdCI6MTU5Mzk1ODIzOH0.AUjS7ocjp3Z_HuU1QqBPUG4NlNcRAihjOhbKBAC_6ecjjlZQM417M9KKGEk1uAr0yKFl9dcPNo04YPSKs-vJ7g"}

401 Unauthorized

{"type":"https://tools.ietf.org/html/rfc7235#section-3.1","title":"Unauthorized","status":401,"traceId":"|9ca7ae31-444c9220bfc1657b.1.88f5b6d2_"}

API's action for example

public async Task<IActionResult> Login(LoginModel loginModel)
    {
        if (ModelState.IsValid)
        {
            Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync
                (loginModel.Email, loginModel.Password, loginModel.RememberMe, false);

            if (result.Succeeded)
            {
                User user = await _userManager.FindByNameAsync(loginModel.Email);
                ServiceResponse response = new ServiceResponse()
                {
                    Result = result,
                    Token = CreateToken(user)
                };
                return Ok(response);
            }
            else
            {
                return Unauthorized();
            }
        }
        return NoContent();

    }

Upvotes: 0

Views: 1550

Answers (1)

Arsalan Valoojerdi
Arsalan Valoojerdi

Reputation: 1026

You should create a model for your responses and return all of your responses in that structure.

Example:

public class ResponseModel
{
    public bool Succeeded { get; set; }
    
    public string Message { get; set; }
    
    public object Content { get; set; }
}

Ok Response structure : 
{
    "succeeded" : true,
    "message" : "some-message",
    "content" : {
        "isLockedOut" : false,
        "isNotAllowed" : false,
        ...
        ..
    } 
}

UnAuthorized Response structure :
{
    "succeeded" : false,
    "message" : "some-message",
    "content" : {
        "title" : "unauthorized",
        "status" : "401",
        ...
        ...
    } 
}

Upvotes: 1

Related Questions