标签: asp.net-core-mvc

.NET Core 中的模拟 System.Security.Permissions

我正在尝试将项目移植到 .NET Core,但找不到模拟 System.Security.Permissions。项目使用这样的结构

[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] or [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)], ''

asp.net-core-mvc .net-core asp.net-core asp.net-core-1.0

1
推荐指数
1
解决办法
3863
查看次数

包括所有匹配regex razor cshtml的文件

我想在 CSHTML 文件中包含 Angular2 构建文件。

目前,我的包括:

@section scripts {
    <script src="~/dist/main.js" asp-append-version="true"></script>
}
Run Code Online (Sandbox Code Playgroud)

但是 Angular2 会在每个 prod 构建中生成文件名中具有不同标识符的文件。

chunk    {0} main.2e0750e4cb976b8dca8a.bundle.js (main) 15.8 kB {3} [initial] [rendered]
chunk    {1} styles.b64dd2f7c2e3011c4efb.bundle.css (styles) 154 kB {4} [initial] [rendered]
chunk    {2} scripts.e7e62c29938f18f13e86.bundle.js (scripts) 128 kB {4} [initial] [rendered]
chunk    {3} vendor.05b8df0708b580c61647.bundle.js (vendor) 3.42 MB [initial] [rendered]
chunk    {4} inline.1b4aa06545162c1bb581.bundle.js (inline) 0 bytes [entry] [rendered]
Run Code Online (Sandbox Code Playgroud)

我不想停用(如果可能的话)包含这些标识符的事实(用于非缓存目的)。一个人在 github 问题页面上回答了一些正则表达式可以用来制作包含:

/(main|styles|scripts|vendor|inline).*.bundle.(map|js|css)/g
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将它传递给我的 C#/cshtml 文件。

它应该导致在给定目录(wwwroot 或 ~ 作为快捷方式)中包含与模式匹配的所有文件

关于如何实现这一目标的任何想法?

c# razor asp.net-core-mvc asp.net-core

1
推荐指数
1
解决办法
803
查看次数

FK 和 PK 实体框架核心之间的冲突

我试图建立与实体框架核心的Web应用程序,我创建了两个型号CategoryPie,我做的所有事情,包括的DbContext的依赖注入,我创建了一个DbInializer类来检查,如果数据库是空的,如果这是真的,那会插入一些数据,问题是当我运行应用程序时出现异常,好像类别表中的主键和 Pies 表中的外键之间存在冲突,这是异常:

 System.Data.SqlClient.SqlException: The MERGE statement conflicted with the FOREIGN KEY constraint "FK_Pies_Categories_CategoryId".The conflict occurred in database "ShopDb", table "dbo.Categories", column 'CategoryId'.
     at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean & dataReady)
   at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean & moreRows)
   at System.Data.SqlClient.SqlDataReader.TryHasMoreResults(Boolean & moreResults)
   at System.Data.SqlClient.SqlDataReader.TryNextResult(Boolean & more)
   at System.Data.SqlClient.SqlDataReader.NextResult()
   at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Consume(DbDataReader reader)
ClientConnectionId: 775a7294 - 531a - 44cc …
Run Code Online (Sandbox Code Playgroud)

c# sql-server entity-framework asp.net-core-mvc

1
推荐指数
1
解决办法
1666
查看次数

如何在asp.net核心的configure方法中获取HttpContext?

我有 asp.net 核心应用程序,我想在配置方法中使用当前的 HttpContext。所以我传递IHttpContextAccessor给配置方法。像下面这样

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, 
                      IApplicationLifetime appLifetime, IServiceProvider services, 
                      IHttpContextAccessor httpContextAccessor)
{    
           var request = httpContextAccessor.HttpContext.Request;    
}
Run Code Online (Sandbox Code Playgroud)

但是 httpContextAccessor.HttpContext 始终为 null

asp.net-core-mvc coreclr asp.net-core

1
推荐指数
1
解决办法
1539
查看次数

Self referencing loop from Newtonsoft JsonSerializer using Entity Framework Core

I've encountered the error:

JsonSerializationException: Self referencing loop detected for property 'Subject' with type 'Project.Models.Subject'. Path 'data[0].Totals'.

It occurs when I load a View with a dataGrid populated by an IEnumerable<Subject> model. The Grid is a DevExtreme DataGrid bound to the View's model like this:

@(Html.DevExtreme().DataGrid()
    .DataSource(Model)
    .Paging(paging =>
    {
        paging.Enabled(true);
        paging.PageIndex(0);
        paging.PageSize(20);
    })
    .Columns(columns =>
    {
        columns.Add().DataField("SubjectId");
        ... other fields
    })
)
Run Code Online (Sandbox Code Playgroud)

Which is populated from a Controller that pulls data from a Repository with this function:

public async …
Run Code Online (Sandbox Code Playgroud)

c# json.net devextreme entity-framework-core asp.net-core-mvc

1
推荐指数
1
解决办法
2755
查看次数

模拟 Url.RouteUrl

我使用Asp.netCore并且以下代码是我需要测试的操作的一部分XUnit。问题是URL在我测试操作方法时哪个为空。我如何模拟URL及其功能RoutUrl来返回URL我期望的。

var callbackUrl = Url.RouteUrl("ConfirmEmail", new { userId = user.Id, token }, Request.Scheme);
Run Code Online (Sandbox Code Playgroud)

我也试过这段代码,但它根本不起作用。

string locationUrl = "http://location/";
var mockUrlHelper = new Mock<IUrlHelper>();
mockUrlHelper
    .Setup(x => x.RoutUrl("ConfirmEmail", It.IsAny<object>(), It.IsAny<string>()))
    .Returns(locationUrl);

_accountController.Url = mockUrlHelper.Object;
Run Code Online (Sandbox Code Playgroud)

这是我正在测试的操作方法:

[HttpPost]
public async Task<JsonResult> SendEmailConfirmation(string email)
{
    if (string.IsNullOrEmpty(email)) throw new Exception("Inavlid parameter");

    var user = await _userManager.GetUserAsync(User);

    if (user.Email.ToLower() == email.ToLower().Trim())
        return Json(false);

    user.EmailConfirmed = false;
    user.Email = email;
    await _userManager.UpdateAsync(user);

    var token …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq xunit asp.net-core-mvc

1
推荐指数
1
解决办法
1253
查看次数

对于数据验证,在哪里添加 Html.RenderPartialAsync("_ValidationScriptsPartial")?

在我的ASP.NET Core 1.1.1应用程序中,模型验证不起作用。我注意到一些默认值views(例如login.cshtmlRegister.cshtml在创建VS2017应用程序时创建的)在末尾具有以下代码。但这些默认视图实际上是局部视图。我的视图不是局部视图,是否也应将以下内容添加到我的末尾views?或者我应该在不是部分视图的视图末尾添加什么:

@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
Run Code Online (Sandbox Code Playgroud)

validation data-annotations razor asp.net-core-mvc

1
推荐指数
1
解决办法
7839
查看次数

如何从 ILogger 中获取我的自定义 ILogger 实现,例如控制器?

我有一个自定义记录器,我想创建一个名为的扩展方法

SetContext(uniqueKey, object) 
Run Code Online (Sandbox Code Playgroud)

我可以在我的自定义记录器中设置一个属性并在记录消息时记录该上下文。

所以代码看起来像这样

_logger
     .SetContext(User.Email(), User)
           .LogError(1, new Exception("foo foo foo"), "bleep Bloop");
Run Code Online (Sandbox Code Playgroud)

我似乎面临的问题是,通过控制器中的 DI 返回的 ILogger 又由我的扩展方法使用,实际上并不是我的自定义 ILogger 实现。

 public static ILogger SetContext(this ILogger logger, string uniqueUserIdentifier, object context)
    {
        var redisPublisherLogger = logger as RedisPublisherLogger;

        if (redisPublisherLogger == null)
        {
            return logger;
        }

        redisPublisherLogger.Context = new LoggingContext
        {
            ContextData = context,
            UniqueUserIdentifier = uniqueUserIdentifier
        };

        return logger;
    }
Run Code Online (Sandbox Code Playgroud)

所以无论如何我可以做这样的事情,我试图避免覆盖 ILogger 上的所有日志记录方法。

任何帮助,将不胜感激!谢谢

logging error-logging dependency-injection asp.net-core-mvc asp.net-core

1
推荐指数
1
解决办法
3638
查看次数

ASP.NET Core MVC 加密/解密 QueryString 值

我正在使用 ASP.NET Core 2.0 MVC、C#、Entity Framework Core Code First 和 SQL Server 2016。

我创建了一个 Web 表单,我所有的 CRUD 操作都运行良好。但是,我需要一些关于加密/解密传递给确认、编辑和删除视图的查询字符串值的帮助。

在我的“索引”页面上,当用户将鼠标悬停在指向这些操作方法的“编辑”和“删除”链接上时,我还想对 EmployeeID 进行加密。我不希望它们在索引页上可见。

请参阅我下面的代码。

楷模

public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int DepartmentID { get; set; }
    public Department Department { get; set; }

    public int AppointmentID { get; set; }
    public Appointment Appointment { get; set; }
}

public class Department …
Run Code Online (Sandbox Code Playgroud)

c# encryption asp.net-core-mvc asp.net-core-2.0 asp.net-core-mvc-2.0

1
推荐指数
1
解决办法
1万
查看次数

无法访问 HttpResponseMessage 的正文

我目前正在使用 .NET Core Web App 开发 API 以进行测试,但我一直坚持这个。

实际上,我有这个代码:

namespace CoreWebApp.API.Admin
{
    [Route("api/country")]
    public class CountryController : Controller
    {
        // GET: api/country
        [HttpGet]
        public HttpResponseMessage Get()
        {
            List<Country> countries = Shared.Database.SqlAction.CountriesTable.GetCountries();
            return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(countries), Encoding.UTF8, "application/json") };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是返回一个HttpStatusCode和一个HttpContent。然后我应该在 Postman 上得到它:

[
    {
        "Name":"France"
    },
    {
        "Name":"Germany"
    },
    {
        "Name":"Spain"
    },
    ....
]
Run Code Online (Sandbox Code Playgroud)

状态代码 OK 200


但是,我根本没有得到这个身体,我得到的是:

{
    "version": {
        "major": 1,
        "minor": 1,
        "build": -1,
        "revision": -1,
        "majorRevision": …
Run Code Online (Sandbox Code Playgroud)

c# httpresponse httpcontent asp.net-core-mvc asp.net-core

1
推荐指数
1
解决办法
1253
查看次数