【问题标题】:c# WebAPI API Issue - Swagger - Angular Axiosc# WebAPI API 问题 - Swagger - Angular Axios
【发布时间】:2021-08-03 01:11:36
【问题描述】:

我有一个问题,我不知道该怎么做,问题是在我的 C# WebApi 应用程序上启用了 swagger。

我有一些 api,但这里是其中的一个示例。

[HttpPost]
[Route("/api/user/register")]
public UserSession Register(string email, string password, string confirm_password)
{
    if (password != confirm_password)
    {
        return new UserSession()
        {
            Success = false,
            Message = "Error Passwords don't match",
            SessionKey = "",
        };
    }
    // success code here
}             

这里是 Angular API。

import axios from 'axios';

export class API {
    private static base_api:string = "http://localhost:51019/";
    static register(email:string, password:any, confirm_password:any) {
        let url = this.base_api + "api/user/register";
        let data = {
            email: email,
            password: password,
           confirm_password: confirm_password,
        };    
        const headers = {
            'Content-Type': 'application/json'
        };
        let result = axios.post(url, data, {headers}).then(x=>{return x}).catch(x=>{return false;});
        console.log(result);
    }
}

即使我提供了电子邮件和/或密码,API 也没有收到数据?

为了解决我的 cor 问题,我将它添加到 api 控制器

[HttpOptions]
[Route("/api/user/register")]
[Route("/api/user/login")]
[Route("/api/user/logout")]
public HttpResponseMessage Options()
{
    var response = new HttpResponseMessage();
    response.StatusCode = HttpStatusCode.OK;
    return response;
}

如果我通过 (http://localhost:51019/swagger/index.html) 通过 swagger ui 访问 api

然后当我通过 UI 执行 api 时,它可以正常工作。

TIA

【问题讨论】:

    标签: c# angular api axios


    【解决方案1】:

    通常您会创建一个模型并将其设置为主体:

    public sealed class RegisterModel
    {
        [JsonPropertyName("email")]
        public string Email { get; set; }
    
        [JsonPropertyName("password")]
        public string Password { get; set; }
    
        [JsonPropertyName("confirm_password")]
        public string ConfirmPassword { get; set; }
    }
    
    [HttpPost, Route("/api/user/register")]
    public UserSession Register([FromBody] RegisterModel register)
    {
        // ...
    }
    

    这将使它在所有情况下都能正常工作

    【讨论】:

      猜你喜欢
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      相关资源
      最近更新 更多