1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ローカル環境で.NET(C#)にAngular(Typescript)からhttpリクエストを送付する方法

1
Last updated at Posted at 2025-07-15

こんにちは。初学者のHiroと申します。
今回は実装していく中でなるほどなぁ。。。と思ったHTTPリクエストの基礎部分の実装を考えてみました。

下記記載の内容を行えば、ひとまずHTTP通信でFrontとBackをつなげることができるはずです。

1.TypeScript側の設定

app.config.tsにproviderHttpClient() を設定する。

app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideHttpClient(),
  ],
};

今回は、お試しのため適当に作成した「hello.components.ts」にhttpリクエストを記載する。
下記内容を定めれば最低限のhttpリクエストを送ることは可能。

hello.components.ts
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hello',
  imports: [CommonModule],
  templateUrl: './hello.component.html',
  styleUrl: './hello.component.css',
})
export class HelloComponent implements OnInit {
  title: string = '';

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.title = 'hello';
    this.httpClient
      .get<Object>('https://localhost:7010/api/user/index')
      .subscribe((object) => {
        console.log(object);
      });
  }
}

返却値をObjectに指定することで、
「レスポンスは型に関係なく受け取れる汎用的なオブジェクト」 として扱われます。
つまり、どんなJSON構造でも型チェックなしでobjectとして受け取れます。
anyと記載しても似たような動作をします。

ただ、型チェック等が効かないため、ちゃんとしたレスポンスを受け取りたい場合は型を指定してあげることが好ましいです。(というか、実務ではそうであるべき)

2. .NET(C#)側の設定

httpリクエストを受け付けられるようにしておきます。

2-1.Controllerの設定

今回はユーザーデータ(ID,氏名,メールアドレス)を返却する簡易Controllerを用意します。

UserController.ts
 [Route("api/[controller]/[action]")]
 public class UserController : ControllerBase
 {
     private readonly UserDataService service;
    
     public UserController(UserDataService service)
     {
         this.service = service;
     }
 
     [HttpGet]
     public IActionResult Index()
     {
         return Ok(this.service.GetAllUserData());
     }

serviceでの実装は省略しますが、ここでは、下記のようなデータを返却するものとします。

User.json
{
    "users": [
        {
            "id": 1,
            "userName": "テス子",
            "email": "tesuko@test.com"
        },
        {
            "id": 2,
            "userName": "テス男",
            "email": "tesuo@test.com"
        },
        {
            "id": 3,
            "userName": "テス次郎",
            "email": "tesujiro@test.com"
        }
    ]
}

2-2.Program.csの設定

しかし、これで起動できるわけではありません。
ブラウザのセキュリティ機能(CORS)が動作し、フロントエンドからのリクエストをブロックしてしてしまう可能性があります。
そのため、下記のようにProgram.csに追記してフロントからのリクエストを受け入れられる状態にする必要があります。

Program.cs
// CORSポリシーの名前を定義
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

// CORSポリシーを追加
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
        builder =>
        {
          // ここにAngularアプリのURLを正確に記述
          // 例: Angularがhttp://localhost:4200で動いている場合
          builder.WithOrigins("http://localhost:4200","https://localhost:4200") // 必要であればHTTPSも
                 .AllowAnyHeader() // 全てのヘッダーを許可 (開発用)
                 .AllowAnyMethod(); // 全てのHTTPメソッドを許可 (開発用)
                                    // .AllowCredentials(); // クッキーや認証ヘッダーを送る場合はこれも必要
        });
});

var app = builder.Build();
app.UseCors(MyAllowSpecificOrigins);

1点注意するべきは、ポリシーに関しては「var app = builder.Build();」の上に記載することです。
そうでないとうまく動かなくなるようです。

さいごに

最後までお読みいただきありがとうございます。
上記内容がうまく実装できれば、ひとまずHTTP通信でのリクエスト送付はできると思います。

実はこれが私の最初の記事でして、先駆者様方の記事と比べると非常に見づらいとは思いますが、、、誰かの助けになれればいいなと思い、これからも続けていきたいと思います!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?