2

Currently, I'm writing a web application in C# ASP.NET Core and Razor Pages.

In the future I want to replace my frontend with an Angular application. Now I'm wondering how to set up my controllers to serve both technologies.

The problem is, that my controller methods have to return a ViewResult object to properly render the view when using Razor Pages. The result obviously can't be used in Angular and the controller methods aren't really RESTful which I want them to be.

So is there a way to implement a controller supporting Razor and Angular?

Thanks in advance

1
  • Try to move logic from the controller method somewhere else. You can use MediatR to implement CQS or CQSR pattern. Or write special services and call command/query (service method) in controller Commented Feb 13, 2020 at 21:11

1 Answer 1

1

If you are going the angular way, not really. Angular expects communication using Xhr requests.

There is even a template in net core for angular applications: https://learn.microsoft.com/en-us/aspnet/core/client-side/spa/angular?view=aspnetcore-3.1&tabs=visual-studio

In theory you could achieve what you want with some duplication.

I.e.:

[HttpGet]
public ActionResult Index()
{
     IndexViewModel viewModel = GetIndexModel();
     // Add action logic here
     return View(viewModel);
}

[HttpGet]
public IndexViewModel GetIndexModel() {
   // return the view model.
}

The second get function can be used as xhr request from your angular application. This is not really recommended. Going angular is a good opportunity to turn your api to Rest and properly handle the data in your spa.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.