Asp. Net Почтовый запрос Core 3.1 не работает с Angular 8 на сервере - PullRequest
0 голосов
/ 14 июля 2020

Работает по локальному запросу или по запросу почтальона. Но когда я публикую файлы, появляется «Неизвестная ошибка». Я использую Windows аутентификацию. Я пробовал его с Firefox, затем получаю следующую ошибку: firefox ошибка . Когда я взял Firefox необработанный запрос и вставил его в Postman, это сработало.

Вот мой метод контроллера:

    [HttpPost]
    public ApiResult<OverTimePlanning> Post([FromBody]OverTimePlanning overTimePlanning)
    {
        logger.LogInformation("Planning Add started");
        var result = new OverTimePlanning();
        var apiResult = new ApiResult<OverTimePlanning>();
        ... Some codes are here ...
        logger.LogInformation("Planning Add ended");
        return apiResult;
    }

Вот мой класс модели C# :

public class OverTimePlanning
{
    public int ID { get; set; }
    public Guid GUID { get; set; }
    public string Unit { get; set; }
    public DateTime DateStarted { get; set; }
    public DateTime DateEnded { get; set; }
    public int? ApproverUserId { get; set; }
    public string ApproverUser { get; set; }
    public string ApproverUserPhoto { get; set; }
    public string Description { get; set; }
    public string ShortDescription { get; set; }
    public OnayDurumu Status { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateUpdated { get; set; }
    public int UserCreatedId { get; set; }
    public string UserCreated { get; set; }
    public string UserPhoto { get; set; }
    public string ApproverComment { get; set; }
    /// <summary>
    /// Employee list
    /// </summary>
    public IEnumerable<OrganisationUser> Employees { get; set; } 
}

public class OrganisationUser
{
    public int ID { get; set; }
    public int EmployeeID { get; set; }
    public string Name  { get; set; }
    public string ShortName { get; set; }
    public string UserName { get; set; }
    public string Email  { get; set; }
    public string Photo    { get; set; }
    public string Manager { get; set; }
    public string Unit { get; set; }
    public int Level { get; set; }
   
}

Вот мой Angular код услуги:

saveOverTimePlanning(overtime: OverTimePlanning) {
const header = new HttpHeaders().set('Content-Type', 'application/json');
const options = { headers: header, withCredentials: true };
return this.http.post(this.apiUrl, JSON.stringify(overtime).replace(/_/g, ''), options);
}

Вот моя Angular модель:

import { OrganisationUser } from './organisationUser.model'
export class OverTimePlanning {
private _id: number
public get id(): number {
    return this._id
}
public set id(value: number) {
    this._id = value
}
private _guid: string
public get guid(): string {
    return this._guid
}
public set guid(value: string) {
    this._guid = value
}
private _unit: string
public get unit(): string {
    return this._unit
}
public set unit(value: string) {
    this._unit = value
}
private _dateStarted: Date
public get dateStarted(): Date {
    return this._dateStarted
}
public set dateStarted(value: Date) {
    this._dateStarted = value
}
private _dateEnded: Date
public get dateEnded(): Date {
    return this._dateEnded
}
public set dateEnded(value: Date) {
    this._dateEnded = value
}
private _approverUserId: number
public get approverUserId(): number {
    return this._approverUserId
}
public set approverUserId(value: number) {
    this._approverUserId = value
}
private _approverUser: string
public get approverUser(): string {
    return this._approverUser
}
public set approverUser(value: string) {
    this._approverUser = value
}
private _approverUserPhoto: string
public get approverUserPhoto(): string {
    return this._approverUserPhoto
}
public set approverUserPhoto(value: string) {
    this._approverUserPhoto = value
}
private _description: string
public get description(): string {
    return this._description
}
public set description(value: string) {
    this._description = value
}
private _shortDescription: string
public get shortDescription(): string {
    return this._shortDescription
}
public set shortDescription(value: string) {
    this._shortDescription = value
}
private _status: number
public get status(): number {
    return this._status
}
public set status(value: number) {
    this._status = value
}
private _dateCreated: Date
public get dateCreated(): Date {
    return this._dateCreated
}
public set dateCreated(value: Date) {
    this._dateCreated = value
}
private _dateUpdated: Date
public get dateUpdated(): Date {
    return this._dateUpdated
}
public set dateUpdated(value: Date) {
    this._dateUpdated = value
}
private _userCreatedId: number
public get userCreatedId(): number {
    return this._userCreatedId
}
public set userCreatedId(value: number) {
    this._userCreatedId = value
}
private _userCreated: string
public get userCreated(): string {
    return this._userCreated
}
public set userCreated(value: string) {
    this._userCreated = value
}
private _userPhoto: string
public get userPhoto(): string {
    return this._userPhoto
}
public set userPhoto(value: string) {
    this._userPhoto = value
}
private _approverComment: string
public get approverComment(): string {
    return this._approverComment
}
public set approverComment(value: string) {
    this._approverComment = value
}

private _employees: OrganisationUser[]
public get employees(): OrganisationUser[] {
    return this._employees
}
public set employees(value: OrganisationUser[]) {
    this._employees = value
}

}

export class OrganisationUser {
private _id: number;
public get id(): number {
    return this._id;
}
public set id(value: number) {
    this._id = value;
}
private _employeeID: number;
public get employeeID(): number {
    return this._employeeID;
}
public set employeeID(value: number) {
    this._employeeID = value;
}
private _name: string;
public get name(): string {
    return this._name;
}
public set name(value: string) {
    this._name = value;
}
private _shortName: string;
public get shortName(): string {
    return this._shortName;
}
public set shortName(value: string) {
    this._shortName = value;
}
private _userName: string;
public get userName(): string {
    return this._userName;
}
public set userName(value: string) {
    this._userName = value;
}
private _email: string;
public get email(): string {
    return this._email;
}
public set email(value: string) {
    this._email = value;
}
private _photo: string;
public get photo(): string {
    return this._photo;
}
public set photo(value: string) {
    this._photo = value;
}
private _manager: string;
public get manager(): string {
    return this._manager;
}
public set manager(value: string) {
    this._manager = value;
}
private _unit: string;
public get unit(): string {
    return this._unit;
}
public set unit(value: string) {
    this._unit = value;
}
private _level_: number;
public get level_(): number {
    return this._level_;
}
public set level_(value: number) {
    this._level_ = value;
}
}

Ответы [ 2 ]

0 голосов
/ 21 июля 2020

Я узнал следующее: вы не можете отправлять необработанные / json данные запроса с Windows учетными данными. Поскольку новейшие браузеры не поддерживают предварительные запросы (HttpOptions) с учетными данными Windows.

0 голосов
/ 14 июля 2020

Нулевой код состояния обычно является причиной ошибки CORS. Проверьте реализацию CORS на стороне сервера.

Вот официальная документация промежуточного программного обеспечения CORS в. net: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

При запуске просто включите промежуточное ПО : (из документов):

 readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins("http://example.com",
                                                  "http://www.contoso.com");
                          });
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{       
    app.UseCors(MyAllowSpecificOrigins);
   
}
...