c# - .net 核心 IActionResult 返回 OK()

标签 c# asp.net-core .net-core

我已经按照下一个例子 Link to source

当我创建我的 Controller (应该与他的 TripsController 相同)以返回带有数据的 Ok 时,浏览器未解析为 HTML,它仅在浏览器中显示 json 格式。

using System;
using System.Collections.Generic;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RnD.Models.Repository;
using RnD.Models.ViewModels;

namespace RnD.Controllers.Web
{

    [Route("/machines")]
    [Authorize]
    public class MachineTypeController : Controller
    {
        private ILogger<MachineTypeController> _logger;
        private IMachineTypeRepository _repository;

        public MachineTypeController(IMachineTypeRepository repository, ILogger<MachineTypeController> logger)
        {
            _logger = logger;
            _repository = repository;
        }

        [HttpGet("")]
        public IActionResult Index()
        {
            try
            {
                var results = _repository.GetAllMachineTypes();

                return Ok(Mapper.Map<IEnumerable<MachineTypeViewModel>>(results));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to get all Machine types: {ex}");
                return BadRequest("Error Occurred");
            }

        }
    }
}

如果我返回 View ,它将正常工作。

这是Startup.cs

using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using RnD.Models.DataFixtures;
using RnD.Models.Entity;
using RnD.Models.Repository;
using RnD.Models.ViewModels;

namespace RnD
{
    public class Startup
    {
        private IHostingEnvironment _env;
        private IConfigurationRoot _config;

        public Startup(IHostingEnvironment env)
        {
            _env = env;

            var builder = new ConfigurationBuilder()
                .SetBasePath(_env.ContentRootPath)
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();

            _config = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_config);

            services.AddDbContext<RnDContext>();

            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail = false;
                config.Password.RequireDigit = false;
                config.Password.RequireUppercase = false;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/auth/login";
                config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = async ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 401;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        await Task.Yield();

                    }
                };
            }).AddEntityFrameworkStores<RnDContext>();

            services.AddScoped<IMachineTypeRepository, MachineTypeRepository>();

            services.AddTransient<RnDContextSeedData>();

            services.AddLogging();

            services.AddMvc(config =>
            {
                if (_env.IsProduction())
                {
                    config.Filters.Add(new RequireHttpsAttribute());
                }
            })
            .AddJsonOptions(config =>
            {
                config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            RnDContextSeedData seeder,
            ILoggerFactory loggerFactory

            )
        {

            Mapper.Initialize(config =>
            {
                config.CreateMap<MachineTypeViewModel, MachineType>().ReverseMap();
            });
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                loggerFactory.AddDebug(LogLevel.Information);
            }
            else
            {
                loggerFactory.AddDebug(LogLevel.Error);
            }
            app.UseStaticFiles();
            app.UseIdentity();
            app.UseMvc(config =>
            {
                config.MapRoute(
                  name: "Default",
                  template: "{controller}/{action}/{id?}",
                  defaults: new { controller = "Home", action = "Index" }
                  );
            });

            seeder.EnsureSeedData().Wait();
        }
    }
}

这里是angular的代码

应用程序.js

// app.js
(function () {
    "use strict";

    angular.module("app",[]);
})();

机器 Controller .js

// machineController.js
(function () {
    "use strict";

    angular.module("app")
        .controller("machineController", machineController);



    function machineController($http) {
        /* jshint validthis:true */
        var vm = this;

        vm.machines = [];

        vm.errorMessage = "";

        $http.get("/machines")
            .then(function (response) {
                // Success
                angular.copy(response.data, vm.machines);
            }, function (error) {
                // Failure
                vm.errorMessage = "Failed: " + error;
            });

    }
})();

索引.cshtml

@model IEnumerable<RnD.Models.Entity.MachineType>
@{
    ViewBag.Title = "Machine Type List";
}

@section scripts{

    <script src="~/lib/angular/angular.js"></script>
    <script src="~/js/app.js"></script>
    <script src="~/js/machineController.js"></script>
}
<div class="row" ng-app="app">
    <div ng-controller="machineController as vm" class="col-md-6 col-md-offset-6">
        <table class="table table-responsive">
            <tr ng-repeat="machine in vm.machines">
                <td>{{machine.name}}</td>
            </tr>
        </table>
    </div>
</div>

最佳答案

我找到了问题所在。

  1. 在 Controller 中我添加了一个方法

    [HttpGet("GetMachines")]
    public IActionResult GetMachines()
    {
        try
        {
            var results = _repository.GetAllMachineTypes();
    
            return Ok(Mapper.Map<IEnumerable<MachineTypeViewModel>>(results));
        }
        catch (Exception ex)
        {
            _logger.LogError($"Failed to get all Machine types: {ex}");
            return BadRequest("Error Occurred");
        }
    }
    
  2. 其次我更改了 machineController.js

    (function () {
    "use strict";
    
    angular.module("app")
        .controller("machineController", machineController);
    
    
    
    function machineController($http) {
        /* jshint validthis:true */
        var vm = this;
    
        vm.machines = [];
    
        vm.errorMessage = "";
    
        $http.get("/machines/GetMachines")
            .then(function (response) {
                // Success
                angular.copy(response.data, vm.machines);
            }, function (error) {
                // Failure
                vm.errorMessage = "Failed: " + error;
            });
    
    }
     })();
    

关于c# - .net 核心 IActionResult 返回 OK(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44949170/

相关文章:

c# - 如何解决 SqlNullValueException?

.net - 将一次性应用程序替换为 msix 对应应用程序

c# - 动态添加的 DropDownlists 未触发 SelectedIndexChanged 事件

c# - 如何使用 AbotX Javascriptrendering 在网页上覆盖和执行操作

c# - 自动序列化 JSON 以更正对象类型

jquery - 用于加载 jquery.unobtrusive-ajax.js 的 asp-fallback-test

c# - 当文本超过一定长度时换行到下一行?

c# - 为什么 Task.Run 中的这种包装可以消除 ASP.NET Core 中的死锁?

c# - 浏览器关闭后 ASP.NET Core Auth 不会保持登录状态 (Azure AD B2C)

visual-studio-2017 - Netstandard.Library 1.6.1 被项目阻止