标签: asp.net-core

如何在ASP.NET Core中获取HttpContext.Current?

我们目前正在使用ASP.NET Core重写/转换我们的ASP.NET WebForms应用程序.尽量避免重新设计.

我们HttpContext在类库中使用了一个部分来检查当前状态.如何HttpContext.Current在.NET Core 1.0中访问?

 var current = HttpContext.Current;
     if (current == null)
      {
       // do something here
       // string connection = Configuration.GetConnectionString("MyDb");
      }
Run Code Online (Sandbox Code Playgroud)

我需要访问它才能构建当前的应用程序主机.

$"{current.Request.Url.Scheme}://{current.Request.Url.Host}{(current.Request.Url.Port == 80 ? "" : ":" + current.Request.Url.Port)}";
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core

182
推荐指数
3
解决办法
19万
查看次数

如何在ASP.NET CORE中获取客户端IP地址?

你能否告诉我如何在使用MVC 6时在ASP.NET中获取客户端IP地址Request.ServerVariables["REMOTE_ADDR"]不起作用.

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

166
推荐指数
13
解决办法
9万
查看次数

node.js与ASP.NET核心性能测试的意外结果

我正在用编写的两个(有点)hello world项目进行快速压力测试.它们都在生产模式下运行,并且没有连接记录器.结果令人惊讶!即使在做了一些额外的工作之后,ASP.NET核心也优于node.js应用程序,而node.js应用程序只是渲染视图.

应用1: http://localhost:3000/nodejs node.js

使用:node.js,express和vash渲染引擎.

nodejs app

此端点中的代码是

router.get('/', function(req, res, next) {
  var vm = {
    title: 'Express',
    time: new Date()
  }
  res.render('index', vm);
});
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,除了通过time变量将当前日期发送到视图之外,它什么也没做.

应用2: http://localhost:5000/aspnet-core asp.net core

使用:ASP.NET Core,默认模板定位dnxcore50

然而,这个应用程序不仅仅是渲染一个带有日期的页面.它生成5段各种随机文本.从理论上讲,这应该比nodejs app重一点.

asp.net核心应用程序

这是呈现此页面的操作方法

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
[Route("aspnet-core")]
public IActionResult Index()
{
    var sb = new StringBuilder(1024);
    GenerateParagraphs(5, sb);

    ViewData["Message"] = sb.ToString();
    return View();
}
Run Code Online (Sandbox Code Playgroud)

压力测试结果

Node.js App压力测试结果

更新:遵循Gorgi Kosev的建议

运用 npm install -g recluster-cli && …

c# performance stress-testing node.js asp.net-core

164
推荐指数
2
解决办法
8万
查看次数

如何在Asp.net core 6 Program.cs文件中使用appsettings.json

我正在尝试访问我的 Asp.net core v6 应用程序 Program.cs 文件中的 appsettings.json,但在此版本的 .Net 中,Startup 类和 Program 类合并在一起,并且 using 和 another 语句被简化并从 Program 中删除。CS。在这种情况下,如何访问 IConfiguration 或如何使用依赖注入?

代码

这是 Asp.net 6 为我创建的默认 Program.cs

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection(); …
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core .net-6.0

161
推荐指数
9
解决办法
23万
查看次数

ASP.NET核心中基于令牌的认证

我正在使用ASP.NET Core应用程序.我正在尝试实现基于令牌的身份验证,但无法弄清楚如何在我的情况下使用新的安全系统.我经历了一些例子,但他们对我没什么帮助,他们使用的是cookie身份验证或外部身份验证(GitHub,Microsoft,Twitter).

我的场景是什么:angularjs应用程序应该请求/tokenurl传递用户名和密码.WebApi应授权用户并返回access_tokenangularjs app在以下请求中使用的内容.

我找到了很好的文章,关于在当前版本的ASP.NET中实现我所需要的 - 使用ASP.NET Web API 2,Owin和Identity进行基于令牌的身份验证.但对我来说,如何在ASP.NET Core中做同样的事情并不明显.

我的问题是:如何配置ASP.NET Core WebApi应用程序以使用基于令牌的身份验证?

c# authentication access-token asp.net-web-api asp.net-core

158
推荐指数
2
解决办法
7万
查看次数

如何在ASP.NET Core中启用CORS

我试图在我的ASP.NET Core Web API上启用跨源资源共享,但我被困住了.

EnableCors属性接受policyName类型string为参数:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);
Run Code Online (Sandbox Code Playgroud)

policyName意味着什么以及如何在ASP.NET Core Web API上配置CORS

c# asp.net-core

154
推荐指数
10
解决办法
11万
查看次数

如何从ASP.NET Core RC2 Web Api返回HTTP 500?

回到RC1,我会这样做:

[HttpPost]
public IActionResult Post([FromBody]string something)
{    
    try{
        // ...
    }
    catch(Exception e)
    {
         return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
    }
}
Run Code Online (Sandbox Code Playgroud)

在RC2中,不再有HttpStatusCodeResult,而且我找不到任何东西可以让我返回500类型的IActionResult.

对于我要问的方法,这种方法现在完全不同吗?我们不再尝试捕获Controller代码吗?我们只是让框架将一个通用500异常抛回API调用者吗?对于开发,我怎样才能看到确切的异常堆栈?

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

154
推荐指数
10
解决办法
12万
查看次数

如何在ASP.net Core WebAPI中启用CORS

我想做什么

我有一个Azure免费计划托管的后端ASP.Net核心Web API(源代码:https://github.com/killerrin/Portfolio-Backend).

我还有一个客户网站,我想要消费该API.客户端应用程序不会托管在Azure上,而是托管在Github Pages或我可以访问的其他Web托管服务上.因此,域名不会排队.

考虑到这一点,我需要在Web API端启用CORS,但是我现在已经尝试了好几个小时并拒绝工作.

我如何设置客户端 它只是一个用React.js编写的简单客户端.我在Jquery中通过AJAX调用API.React网站有效,所以我知道不是这样.Jquery API调用正如我在Attempt 1中确认的那样工作.这是我如何进行调用

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            } …
Run Code Online (Sandbox Code Playgroud)

c# rest cross-domain cors asp.net-core

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

ASP.NET Core Dependency Injection错误:尝试激活时无法解析类型服务

我创建了一个.NET Core MVC应用程序,并使用依赖注入和存储库模式将一个存储库注入我的控制器.但是,我收到一个错误:

InvalidOperationException:尝试激活"WebApplication1.Controllers.BlogController"时,无法解析类型"WebApplication1.Data.BloggerRepository"的服务.

型号(Blog.cs)

namespace WebApplication1.Models
{
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

DbContext(BloggingContext.cs)

using Microsoft.EntityFrameworkCore;
using WebApplication1.Models;

namespace WebApplication1.Data
{
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }
        public DbSet<Blog> Blogs { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

存储库(IBloggerRepository.cs和BloggerRepository.cs)

using System;
using System.Collections.Generic;
using WebApplication1.Models;

namespace WebApplication1.Data
{
    internal interface IBloggerRepository : IDisposable
    {
        IEnumerable<Blog> GetBlogs();

        void InsertBlog(Blog blog);

        void …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection asp.net-core-mvc asp.net-core

146
推荐指数
13
解决办法
18万
查看次数

在ASP.NET Core MVC中选择Tag Helper

我需要帮助ASP.NET Core中的select标签助手.

我有一个员工列表,我正在尝试绑定到选择标记帮助程序.我的员工在一个List<Employee> EmployeesList和选定的价值将进入EmployeeId财产.我的视图模型如下所示:

public class MyViewModel
{
   public int EmployeeId { get; set; }
   public string Comments { get; set; }
   public List<Employee> EmployeesList {get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的员工类看起来像这样:

public class Employee
{
   public int Id { get; set; }
   public string FullName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何告诉我的选择标记助手在下拉列表中Id显示时使用该值作为值FullName

<select asp-for="EmployeeId" asp-items="???" />
Run Code Online (Sandbox Code Playgroud)

我很感激这方面的一些帮助.谢谢.

c# asp.net-core-mvc tag-helpers asp.net-core

141
推荐指数
3
解决办法
15万
查看次数