小编EiE*_*Guy的帖子

如何在环境变量中正确存储连接字符串,以便通过生产ASP.Net Core MVC应用程序进行检索

我正在使用ASP.NET Core MVC应用程序,我的连接字符串存在问题.

我在生产服务器上ASPNETCORE_ENVIRONMENT设置了一个变量Production,我的生产服务器是运行IIS的Windows Server 2012R2.我还在生产服务器上安装了DotNetCore.1.0.4_1.1.1-WindowsHosting.exe.

在开发过程中,我UserSecrets用来保存我的连接字符串.这工作正常.

对于生产,我希望我的生产服务器上的环境变量中的连接字符串,这是我遇到问题的地方.我怀疑它可能是我构建环境变量的方式.

当我尝试在生产中访问数据库时,我得到一个错误,表明它无法解析连接字符串.

An exception occurred in the database while iterating the results of a query.

System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 
parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
Run Code Online (Sandbox Code Playgroud)

如果我将连接字符串放入appSettings.json,生产服务器就可以正常工作.

所以,这是我的appSettings.json文件示例,显示了在生产中工作的连接字符串;

{
  "ConnectionStrings": {
     "TestDb": "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
  },

    ...
    ...
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我将此appSettings.json文件部署到生产中,它可以正常工作.

在我的ASP.Net Core应用程序中,在Startup.cs文件中,我有以下内容:

public Startup(IHostingEnvironment env)
{
    var …
Run Code Online (Sandbox Code Playgroud)

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

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

如何自动将Visual Studio 2017 Web项目发布到文件夹

我正在尝试创建PowerShell v5脚本来构建和发布VS2017 WCF Web服务应用程序(.NET Framework 4),以便我可以在Bamboo中自动执行它.我有msbuild命令正常工作,正确构建,现在我需要使用FolderProfile将项目发布到文件夹.

通过右键单击项目并选择发布,然后选择FolderProfile,我可以手动成功完成.这会将需要部署的文件放在项目的bin\Release\PublishOutput位置中.我想在Powershell脚本中自动化该发布.

我在Sayed Hashimi的网站上尝试了这个建议,类似于下面的内容(我只使用15.2的VS2017版本,当然,用我的实际值替换项目名称和配置文件);

msbuild MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name> /p:Password=<insert-password> /p:VisualStudioVersion=15.2 
Run Code Online (Sandbox Code Playgroud)

但这并没有把任何文件放在该bin\Release\PublishOutput位置.看起来它只是做了一个标准的构建.

编辑:

当我运行上面的命令时,msbuild在输出中列出了这一行;

DeploymentUnpublishable:
    Skipping unpublishable project.
Run Code Online (Sandbox Code Playgroud)

我在GitHub 上看了这篇文章,有些人引用了一个解决方案,更新到VS2017的v15.2,我已经做过了;

Microsoft Visual Studio Enterprise 2017
Version 15.2 (26430.16) Release
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑 - 解决方案

@ Leo-MSFT提供了这个解决方案......

msbuild myproject\myproject.vbproj /p:DeployOnBuild=true /p:PublishProfile=FolderProfile.pubxml /p:Configuration=Release
Run Code Online (Sandbox Code Playgroud)

这将文件放入bin\release\PublishOutput.

我花了好几天寻找这个解决方案,我又增加了其他建议SO各种命令的参数和GitHub的论坛帖子,如/t:Publish,/p:PublishProfileRootFolder/p:VisualStudioVersion=15.2.我删除了那些,只是使用上面的行,最后创建了我需要的已发布输出.

msbuild powershell visual-studio webdeploy visual-studio-2017

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

如何从 ASP.Net Core 中的 SqlServerDBContextOptionsExtensions 获取连接字符串

我正在构建一个 ASP.Net Core API,但我无法找到从 DBContextOptions 获取连接字符串的方法。

我的startup.cs中有DBContext,如下所示;

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddEntityFrameworkSqlServer()
        .AddDbContext<MainContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MainConnection")));

    services.AddMvc()
       .AddJsonOptions(opt =>
        {
            opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });
}
Run Code Online (Sandbox Code Playgroud)

在我的 Context 类中,我有以下构造函数;

public MainContext(DbContextOptions<MainContext> options) : base(options)
{

}
Run Code Online (Sandbox Code Playgroud)

但除非我在 DBContext 类的 OnConfiguring 方法中添加一个实际的连接字符串,否则它不起作用,如下所示;

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    //TODO Move connection string to a secure location
    optionsBuilder.UseSqlServer(@"Server= .....");

}
Run Code Online (Sandbox Code Playgroud)

当我调试并检查 Configuration.GetConnectionString("MainConnection") 中的值时,我可以看到 Startup.cs 正在从 appsettings.json 文件中获取正确的连接字符串。

我认为通过 DI 将选项传递到 DbContext 类会传递连接字符串,但 DbContect 类不起作用,除非我在 OnConfiguring 方法中有那个 optionBuilder.UseSqlServer() …

c# entity-framework-core asp.net-core-mvc asp.net-core asp.net-core-middleware

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

我应该如何在ASP.NET Core 2.0 API中使用HttpClient

我正在开发一个ASP.NET Core 2.0 API,我的API需要调用另一个第三方REST API来上传和检索文件,并获取文件列表和状态信息.我将在Azure中托管API,并计划在我的暂存和生产插槽之间进行蓝绿色部署.

似乎最佳实践的一般共识是在Startup.cs - > ConfigureSerrvices方法中通过DI注册设置HTTPClient的Singleton实例,以便提高性能并避免在我新建一个dispose时可能发生的套接字错误通过Using语句与每次使用的HTTPClient连接.这在以下链接中注明;

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx#Anchor_5

http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/

但是,如果我这样做,那么当我在Azure中进行蓝绿色部署时,我可能面临一个问题,即Singleton实例不会看到任何DNS更改.这在以下链接中注明;

http://byterot.blogspot.co.uk/2016/07/singleton-httpclient-dns.html

https://github.com/dotnet/corefx/issues/11224

http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/

因此,现在普遍的共识是使用静态HTTPClient实例,但控制ServicePoint类的ConnectionLeaseTimeout值,将其设置为较短的值,强制关闭连接以刷新DNS.这篇博客文章甚至讨论了nuget包中的一个漂亮的RestClient组件(Nima的Easy.Common),它正确地解决了ConnectionLeaseTimeout以及缓存的DNS值.

但是,似乎ASP.NET Core 2.0没有完全实现ServicePoint,因此ASP.Net Core 2.0目前不支持这种方法.

任何人都可以建议我在Azure上运行的ASP.NET Core 2.0 API中使用HttpClient的正确方法吗?我希望能够进行蓝绿色部署.那么,我是否应该使用Using语句并在每次使用时新建客户端并且只是遭受性能损失?

看起来似乎必须有一个可靠和高效的解决方案来满足这一共同需求.

design-patterns azure servicepoint dotnet-httpclient asp.net-core-2.0

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

为什么FromQuery不能在我的ASP.Net Core 1.1控制器操作中工作

我正在开发ASP.Net Core 1.1 Web API.我有一个ServiceTypeCode控制器,如下所示;

[Produces("application/json")]
[Route("api/[controller]")]
public class ServiceTypeCodeController : Controller
{ 
    ...
    ...
    ...


    [HttpGet]
    public IActionResult Get([FromQuery] string a_query)
    {
        try
        {
            if (string.IsNullOrEmpty(a_query))
            {
                OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes();
                if (result.Success && result.Result.Count > 0)
                {
                    return Ok(JsonConvert.SerializeObject(result.Result));
                }
            } else
            {
                // Deserialize query into dictionary of strings and StringValues 
                var query = QueryHelpers.ParseQuery(a_query.ToLower());

                if (query.TryGetValue("mailclasscode", out var mailClassCode))
                {
                    if (!string.IsNullOrEmpty(mailClassCode))
                    {
                        OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes(mailClassCode);
                        if (result.Success && result.Result.Count > 0)
                        { …
Run Code Online (Sandbox Code Playgroud)

request.querystring asp.net-core-webapi asp.net-core-1.1

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

如何从发送到ASP.NET核心2.0 API控制器操作的请求中获取身份验证标头

我正在开发ASP.NET Core 2.0 RESTful API.我有一个场景,我需要使用HTTPGet方法在我的API控制器上调用操作,我需要提取用于调用另一个第三方API的用户名和密码值.用户名和密码与当前登录的用户标识无关,它们只是我想从我自己的API中发送到另一个API的值,但我不想只是在查询字符串中传递它们.

我可以在客户端中使用基本身份验证将用户名和密码添加到HttpRequestMessage身份验证标头中,然后在我的ASP.NET Core 2.0 API控制器操作中提取该标头吗?

我的客户端会在调用API的代码中出现类似的内容

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, relativeUrl);
    var byteArray = new UTF8Encoding().GetBytes(string.Format($"username:password"));
    request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Run Code Online (Sandbox Code Playgroud)

而且,我的API控制器动作会启动这样的事情;

    [HttpGet()]
    public IActionResult GetUploadedFileList([FromQuery]int pageNumber, [FromQuery]int pageSize)
    {

        //Extract Authentication header values for username and password

    }
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供如何从HTTPGet请求获取Authorization标头的示例

我意识到我可以使用HTTPPost [FromBody]轻松完成此操作,但我的用例要求此方法为HTTGet.

在此先感谢您的帮助.

编辑1 - 解决方案

由于此链接提供了一些提示,我能够让下面的代码工作.虽然这似乎很多工作,所以如果有人有更好或更清洁的解决方案,请发布你的例子.

    [HttpGet()]
    public IActionResult GetUploadedFiles([FromQuery]int pageNumber, [FromQuery]int pageSize)
    {

        string username = string.Empty;
        string password = string.Empty;

        if (Request.Headers.TryGetValue("Authorization", out StringValues authToken))
        {
            string authHeader = authToken.First(); …
Run Code Online (Sandbox Code Playgroud)

http-headers dotnet-httpclient asp.net-apicontroller asp.net-core-2.0

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

无法转换 Newtonsoft.Json.Linq.JObject 类型的对象,即使我试图转换为具有匹配属性的对象

我正在 VS2017 中使用 ASP.NET Core 2.0。

我正在尝试反序列化一些返回的 JSON,HttpResponseMessage但我收到“无法转换类型的对象...”异常。

这是失败的代码;

FilesUploadedListResponse fileUploadListResponse = new FilesUploadedListResponse();
string jsonResult = response.Content.ReadAsStringAsync().Result;
fileUploadListResponse = (FilesUploadedListResponse)JsonConvert.DeserializeObject(jsonResult);
Run Code Online (Sandbox Code Playgroud)

最后一行是我得到异常的地方......

"Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'FilesUploadedListResponse'."
Run Code Online (Sandbox Code Playgroud)

这是字符串中的实际 Json jsonResult

"{\"uploadedfiles\":[],\"totalResults\":0,\"pageNumber\":0,\"pageSize\":0}"
Run Code Online (Sandbox Code Playgroud)

uploadedFiles此结果中的数组为空,因为还没有上传的文件,但我认为将其设为空不应创建异常,对吗?如果它不为空,它会有类似这样的响应:

{
 "uploadedFiles": [
 {
 "id": 1,
 "createdTime": "July 10, 2017 02:02:25 PM",
 "filename": "20170710_14022507701.jpg",
 "sentTime": "July 10, 2017 02:05:11 PM",
 "fileSize": "124 KB"
 },
 {
 "id": 2,
 "createdTime": "June 05, 2017 09:39:25 AM",
 "filename": "20170605_093907701.jpg",
 "sentTime": "June 05, 2017 …
Run Code Online (Sandbox Code Playgroud)

json.net json-deserialization c#-7.0 httpresponsemessage asp.net-core-2.0

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

为什么使用此代码会出现“无法从方法组转换为类型”错误?

我正在尝试将一些旧版 VB.Net 代码迁移到 C#。我正在使用 Telerik 代码转换器。

这是我遗留的 VB.Net 代码

Public Shared Function GetEnumIntFromString(ByVal value As String, ByVal convertTo As [Enum]) As Integer
    Dim enumValueArray() As Integer

    Try
        If value.Trim.Length > 0 Then
            enumValueArray = [Enum].GetValues(convertTo.GetType)

            For Each i As Integer In enumValueArray
                If value.ToUpper = [Enum].GetName(convertTo.GetType, i).ToUpper Then
                    Return i
                End If
            Next
        End If

        'Return Integer.MinValue
        Throw New Exception("Invalid Enum value.  Cannot convert '" & value & "' to " & convertTo.GetType.ToString)
    Catch ex As Exception
        Throw New Exception(ex.Message) …
Run Code Online (Sandbox Code Playgroud)

c# vb.net enums vb.net-to-c#

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

c#7当使用泛型用于方法参数时我得到方法的类型参数'U'的约束必须匹配接口的约束

我正在尝试创建一个接口和一个具体的实现,其中Interface是泛型类型,其中一个方法有一个泛型参数.

我想保留GetPagedList方法参数resourceParams,这样我就可以为接口的不同实现传递不同的resourceParams对象.

使用下面显示的代码时,我收到错误;

方法'ShippingServicesRepository.GetPagedList(U)'的类型参数'U'的约束必须与接口方法IBaseRepository.GetPagedList(U)的类型参数'U'的约束匹配.请考虑使用显式接口实现

这是我的界面;

public interface IBaseRepository<T> 
{
    bool Save();
    bool Exists(int recordId);
    bool MarkForDeletion(int recordId);
    PagedList<T> GetPagedList<U>(U resourceParams) where U : class;
    T Get(int id);
    void Add(T record);
    void Update(T record);
}
Run Code Online (Sandbox Code Playgroud)

这是我的实施;

public class ShippingServicesRepository<T> : IBaseRepository<T> 
{

    //                      /--- GetPagedList is what is throwing the error
    //                      |
    public PagedList<T> GetPagedList<U> (U resourceParams) where U : ShippingServicesResourceParameters
    {
        try
        {

            var collectionBeforePaging =
                _manifestContext.ShippingServices
                .ApplySort(resourceParams.OrderBy, _propertyMappingService.GetPropertyMapping<ShippingServicesDto, ShippingServices>());
            if (!string.IsNullOrEmpty(resourceParams.SearchQuery))
            {
                var searchQueryForWhereClause = resourceParams.SearchQuery.Trim().ToLowerInvariant();
                collectionBeforePaging = …
Run Code Online (Sandbox Code Playgroud)

c# generics interface .net-core asp.net-core-mvc-2.0

-3
推荐指数
1
解决办法
563
查看次数