如何从ASP.NET MVC向Ionic AngularJS的http.get传输数据?跨域场景求助
Hey Craig, great to hear you've already sorted out CORS—that's often the biggest headache here! Let's walk through the straightforward steps to get your ASP.NET MVC app serving data to your Ionic AngularJS app.
Step 1: Set Up a Data Endpoint in ASP.NET MVC
First, you need to expose your list data as a JSON endpoint that your AngularJS app can call. You have two easy options here:
Option A: Use a Web API Controller (Recommended)
Web API is built for exactly this kind of data transfer. Here's how to set one up:
- In your Visual Studio 2015 project, right-click the Controllers folder → Add → Controller → Select "Web API 2 Controller - Empty".
- Name it something like
ProductsApiController(replace "Products" with your actual data model). - Add code to fetch your data from SQL Server and return it as JSON:
public class ProductsApiController : ApiController { // Replace with your actual DbContext private YourAppDbContext db = new YourAppDbContext(); // GET: api/ProductsApi public IHttpActionResult GetAllProducts() { // Fetch your full list from the database var productList = db.Products.ToList(); // Return the data with a 200 OK response return Ok(productList); } // Clean up the DbContext when done protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }
By default, Web API uses the route api/{controller}/{id}, so your endpoint URL will be http://your-aspnet-server/api/ProductsApi.
Option B: Use a Regular MVC Controller Action
If you don't want to add Web API, you can create a JsonResult action in an existing MVC controller:
public class ProductsController : Controller { private YourAppDbContext db = new YourAppDbContext(); public JsonResult GetProductList() { var productList = db.Products.ToList(); // AllowGet is critical here—MVC blocks GET requests for JsonResult by default return Json(productList, JsonRequestBehavior.AllowGet); } }
The endpoint URL here will be http://your-aspnet-server/Products/GetProductList.
Step 2: Call the Endpoint from Ionic AngularJS
Now, in your Ionic app, use AngularJS's $http.get() to pull the data. Here's how to implement this in a controller:
// Replace 'yourIonicApp' with your actual app module name angular.module('yourIonicApp') .controller('ProductListCtrl', ['$scope', '$http', function($scope, $http) { // Replace this with your ASP.NET server's actual URL and endpoint const apiEndpoint = 'http://your-aspnet-server-url/api/ProductsApi'; // Fetch the data $http.get(apiEndpoint) .then(function(response) { // Store the fetched list in scope to use in your view $scope.products = response.data; console.log('Data loaded successfully:', $scope.products); }) .catch(function(error) { // Handle errors (e.g., server down, invalid data) console.error('Failed to load data:', error); // You could show a user-friendly alert here too alert('Oops! Could not load the product list.'); }); }]);
Display the Data in Your Ionic View
Add an ng-repeat to your Ionic template to render the list:
<ion-view view-title="Product List"> <ion-content> <ion-list> <ion-item ng-repeat="product in products"> <h2>{{product.Name}}</h2> <p>{{product.Description}}</p> <p>Price: {{product.Price | currency}}</p> </ion-item> </ion-list> </ion-content> </ion-view>
Step 3: Debugging & Validation Tips
- Test the endpoint first: Open the ASP.NET endpoint URL directly in a browser. You should see raw JSON data—if not, fix your ASP.NET code before moving to AngularJS.
- Check the network tab: In your browser's developer tools (F12), go to the Network tab. Look for the
GETrequest to your ASP.NET server—check the status code (should be 200) and response data. - Authorization checks: If your ASP.NET endpoint uses
[Authorize], you'll need to handle authentication (e.g., JWT tokens) in your AngularJS app. For public lists, just remove the[Authorize]attribute. - Server accessibility: Make sure your ASP.NET server allows incoming requests from your Ionic app's server. In development, you can set Visual Studio to allow external connections (Project Properties → Web → Server → Select "Local IIS" and set a port, then ensure firewall rules allow traffic on that port).
That's it! With these steps, your Ionic app should be pulling the full list from your ASP.NET MVC app smoothly.
内容的提问来源于stack exchange,提问作者Craig

